Computer >> Computer tutorials >  >> Programming >> Python

How to display a float with two decimal places in Python?


You can use string formatting to format floating point numbers to a fixed width in Python.For example, if you want the decimal points to be aligned with width of 12 characters and 2 digits on the right of the decimal, you can use the following:

 >>>x = 12.35874
>>>print "{:12.2f}".format(x)
     12.36

 You can also achieve this result using string interpolation and formatting. For example:

>>>x = 12.35874
>>>print "% 12.2f" % x
     12.36