How to Format Numbers in Python

Problem –

You want to format a number for output and you want to control the number of digits after decimal or want to add thousand separators or use exponential notations etc.

Solution –

To format a number in python you can use the format function.

In [1]: x = 274.67894

In [2]: # format to 1 decimal place

In [3]: format(x, '0.1f')
Out[3]: '274.7'

In [4]: # format to 2 decimal places

In [5]: format(x, '0.2f')
Out[5]: '274.68'

In [6]: # left justify 10 chars with 1 decimal accuracy

In [7]: format(x, '<10.1f')
Out[7]: '274.7     '

In [8]: # right justify 10 chars with 1 decimal accuracy

In [9]: format(x, '>10.1f')
Out[9]: '     274.7'

In [10]: # centered

In [11]: format(x, '^10.1f')
Out[11]: '  274.7   '

In [12]: y = 1000000

In [13]: # include thousand separator

In [14]: format(y, ',')
Out[14]: '1,000,000'

In [15]: # use exponential notation

In [16]: format(y, 'e')
Out[16]: '1.000000e+06'

In [17]: format(y, 'E')
Out[17]: '1.000000E+06'

In [18]: 

Rating: 1 out of 5.

Leave a Reply