How to format a floating number to fixed width in Python?

PythonServer Side ProgrammingProgramming

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 4 digits on the right of the decimal, you can use the following:

>>> x = 12.35874
>>> print "{:12.4f}".format(x)
     12.3587

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

>>> x = 12.35874
>>> print "% 12.4f" % x
     12.3587
raja
Published on 13-Dec-2017 13:40:12
Advertisements