Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 372
Omar Avatar asked Jan 15 '10 22:01

Omar


People also ask

How do you print floating numbers up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you print float numbers in Python?

To print float values with two decimal places in Python, use the str. format() with “{:. 2f}” as str.


1 Answers

Well I would atleast clean it up as follows:

print "%.2f kg = %.2f lb = %.2f gal = %.2f l" % (var1, var2, var3, var4) 
like image 183
Frank Krueger Avatar answered Sep 25 '22 22:09

Frank Krueger