Format 2 decimal places python

Use str.format[] with “{:.2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

Simple example code use str.format[number] with “{:.2f}” as string and float as a number to return a string representation of the number with two decimal places.

fnum = 7.154327

res = "{:.2f}".format[fnum]

print[res]

Output:

How to display a float with two decimal places?

Answer: Use the string formatting operator for that:

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

OR

print["{:.2f}".format[5]]

Do comment if you have any doubts and suggestions on this Python decimal places code.

Note: IDE: PyCharm 2021.3.3 [Community Edition]

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

If you're using this for currency, and also want the value to be seperated by ,'s you can use

$ {:,.f2}.format[currency_value].

e.g.:

currency_value = 1234.50

$ {:,.f2}.format[currency_value] --> $ 1,234.50

Here is a bit of code I wrote some time ago:

print["> At the end of year " + year_string + " total paid is \t$ {:,.2f}".format[total_paid]]

> At the end of year   1  total paid is         $ 43,806.36
> At the end of year   2  total paid is         $ 87,612.72
> At the end of year   3  total paid is         $ 131,419.08
> At the end of year   4  total paid is         $ 175,225.44
> At the end of year   5  total paid is         $ 219,031.80    At the end of year   6  total paid is         $ 262,838.16
> At the end of year   7  total paid is         $ 306,644.52
> At the end of year   8  total paid is         $ 350,450.88
> At the end of year   9  total paid is         $ 394,257.24
> At the end of year  10  total paid is         $ 438,063.60    At the end of year  11  total paid is         $ 481,869.96
> At the end of year  12  total paid is         $ 525,676.32
> At the end of year  13  total paid is         $ 569,482.68
> At the end of year  14  total paid is         $ 613,289.04
> At the end of year  15  total paid is         $ 657,095.40    At the end of year  16  total paid is         $ 700,901.76
> At the end of year  17  total paid is         $ 744,708.12
> At the end of year  18  total paid is         $ 788,514.48
> At the end of year  19  total paid is         $ 832,320.84
> At the end of year  20  total paid is         $ 876,127.20   

Chủ Đề