-1

I tried :

x = 3.4

print(x - math.floor(x))

In both in console and Jupyter Notebook, the result shows 0.3999999999999999 but why not just 0.4 as the result.

Thanks.

Justin
  • 327
  • 3
  • 13

2 Answers2

1

It is actually not due to python but is inherent to how floats are implemented and would also happen in javascript for instance.

This explanation should answer your question: https://floating-point-gui.de/basic/

If you need to handle it as a decimal, as pointed out you should check the decimal module, or you could round the final result before rendering.

sabiwara
  • 2,775
  • 6
  • 11
0

To get 0.4 you can use the decimal module:

>>> import decimal 
>>> x = decimal.Decimal('3.4')
>>> print(x - math.floor(x))
Decimal('0.4')
Algebra8
  • 1,115
  • 1
  • 10
  • 23