[python] Python, print all floats to 2 decimal places in output

I need to output 4 different floats to two decimal places.

This is what I have:

print '%.2f' % var1,'kg =','%.2f' % var2,'lb =','%.2f' % var3,'gal =','%.2f' % var4,'l'

Which is very unclean, and looks bad. Is there a way to make any float in that out put '%.2f'?

Note: Using Python 2.6.

This question is related to python floating-point string-formatting

The answer is


If you are looking for readability, I believe that this is that code:

print '%(kg).2f kg = %(lb).2f lb = %(gal).2f gal = %(l).2f l' % {
    'kg': var1,
    'lb': var2,
    'gal': var3,
    'l': var4,
}

If you just want to convert the values to nice looking strings do the following:

twodecimals = ["%.2f" % v for v in vars]

Alternatively, you could also print out the units like you have in your question:

vars = [0, 1, 2, 3] # just some example values
units = ['kg', 'lb', 'gal', 'l']
delimiter = ', ' # or however you want the values separated

print delimiter.join(["%.2f %s" % (v,u) for v,u in zip(vars, units)])
Out[189]: '0.00 kg, 1.00 lb, 2.00 gal, 3.00 l'

The second way allows you to easily change the delimiter (tab, spaces, newlines, whatever) to suit your needs easily; the delimiter could also be a function argument instead of being hard-coded.

Edit: To use your 'name = value' syntax simply change the element-wise operation within the list comprehension:

print delimiter.join(["%s = %.2f" % (u,v) for v,u in zip(vars, units)])
Out[190]: 'kg = 0.00, lb = 1.00, gal = 2.00, l = 3.00'

Format String Syntax.

https://docs.python.org/3/library/string.html#formatstrings

from math import pi
var1, var2, var3, var4 = pi, pi*2, pi*3, pi*4
'{:0.2f}, kg={:0.2f}, lb={:0.2f}, gal={:0.2f}'.format(var1, var2, var3, var4)

The output would be:

'3.14, kg=6.28, lb=9.42, gal=12.57'

If what you want is to have the print operation automatically change floats to only show 2 decimal places, consider writing a function to replace 'print'. For instance:

def fp(*args):  # fp means 'floating print'
    tmps = []
    for arg in args:
        if type(arg) is float: arg = round(arg, 2)  # transform only floats
        tmps.append(str(arg))
    print(" ".join(tmps)

Use fp() in place of print ...

fp("PI is", 3.14159) ... instead of ... print "PI is", 3.14159


I have just discovered the round function - it is in Python 2.7, not sure about 2.6. It takes a float and the number of dps as arguments, so round(22.55555, 2) gives the result 22.56.


Not directly in the way you want to write that, no. One of the design tenets of Python is "Explicit is better than implicit" (see import this). This means that it's better to describe what you want rather than having the output format depend on some global formatting setting or something. You could of course format your code differently to make it look nicer:

print         '%.2f' % var1, \
      'kg =' ,'%.2f' % var2, \
      'lb =' ,'%.2f' % var3, \
      'gal =','%.2f' % var4, \
      'l'

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to floating-point

Convert list or numpy array of single element to float in python Convert float to string with precision & number of decimal digits specified? Float and double datatype in Java C convert floating point to int Convert String to Float in Swift How do I change data-type of pandas data frame to string with a defined format? How to check if a float value is a whole number Convert floats to ints in Pandas? Converting Float to Dollars and Cents Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Examples related to string-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format in kotlin string templates Converting Float to Dollars and Cents Chart.js - Formatting Y axis String.Format not work in TypeScript Use StringFormat to add a string to a WPF XAML binding How to format number of decimal places in wpf using style/template? How to left align a fixed width string? Convert Java Date to UTC String Format a Go string without printing?