Display a float with two decimal places in Python


Question

I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 -> 5.00, 5.5 -> 5.50, etc). How can I do this in Python?

1
97
6/15/2012 1:03:44 PM

Accepted Answer

You could use the string formatting operator for that:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

The result of the operator is a string, so you can store it in a variable, print etc.

129
5/27/2011 7:15:30 AM

Since this post might be here for a while, lets also point out python 3 syntax:

"{:.2f}".format(5)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon