Python 3 Float Decimal Points/Precision Python 3 Float Decimal Points/Precision python-3.x python-3.x

Python 3 Float Decimal Points/Precision


The comments state the objective is to print to 2 decimal places.

There's a simple answer for Python 3:

>>> num=3.65>>> "The number is {:.2f}".format(num)'The number is 3.65'

or equivalently with f-strings (Python 3.6+):

>>> num = 3.65>>> f"The number is {num:.2f}"'The number is 3.65'

As always, the float value is an approximation:

>>> "{}".format(num)'3.65'>>> "{:.10f}".format(num)'3.6500000000'>>> "{:.20f}".format(num)'3.64999999999999991118'

I think most use cases will want to work with floats and then only print to a specific precision.

Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.


The simple way to do this is by using the round buit-in.

round(2.6463636263,2) would be displayed as 2.65.


In a word, you can't.

3.65 cannot be represented exactly as a float. The number that you're getting is the nearest number to 3.65 that has an exact float representation.

The difference between (older?) Python 2 and 3 is purely due to the default formatting.

I am seeing the following both in Python 2.7.3 and 3.3.0:

In [1]: 3.65Out[1]: 3.65In [2]: '%.20f' % 3.65Out[2]: '3.64999999999999991118'

For an exact decimal datatype, see decimal.Decimal.