0

I found a behavior in python 3.8 which I do not understand.

I execute the following code:

three = 3 * 1.1
thirty = 30 * 1.1
three_hundred = 300 * 1.1
three_thousand = 3000 * 1.1
print(f"{three} \n"
      f"{thirty} \n"
      f"{three_hundred} \n"
      f"{three_thousand} \n")

Which is basically multiplying values with 1.1. However the output is weird:

3.3000000000000003 
33.0 
330.0 
3300.0000000000005 

Does somebody know why I get so many 0 after I did this calculation? My expectation of the output would be: 3.3, 33.0, 330.0, 3300.0

1 Answers1

1

It is not a Python related problem. You can read this Is floating point math broken? to understand the reason behind this behaviour.

If you want to avoid floating point errors in your projects, you should use the built-in library decimal:

In [1]: from decimal import Decimal as D

In [2]: .1 + .2
Out[2]: 0.30000000000000004

In [3]: D('.1') + D('.2')
Out[3]: Decimal('0.3')

In [4]: float(D('.1') + D('.2'))
Out[4]: 0.3

Mohammad Jafari
  • 1,742
  • 13
  • 17