3

I am confused by the floating-point precision problem in python.

for example: 48.91 multiplies 10000:

> 48.91 * 10000
489099.9999999999994

I lose the precision, but if I directly type in 48.91 as float, it can perfectly represent it.

> 48.91
48.91

> float(48.91)
48.91

So how come sometimes It can keep the precision while sometimes It can't?? How to deal with this situation??

foxhlchen
  • 53
  • 4

1 Answers1

2

Read these articles

https://docs.python.org/3/tutorial/floatingpoint.html

https://blog.tecladocode.com/decimal-vs-float-in-python/

TLDR;

Try to use decimal to handle this case

from decimal import Decimal

num = Decimal('48.91')
print(num * 10000)
Menglong Li
  • 2,177
  • 14
  • 19