1

The Python round() function will theoretically take negative numbers to round to places left of the decimal. [ I.e. round(150, -2) => 200]

However, it seems to be very susceptible to floating point error.

For example, given a large number say 2e25, it gives weird results.

2e25 === 20000000000000000000000000

But, round(2e25, -23) gives a value like 20000000000000000273942742

When it should just be getting 20000000000000000000000000

I know there's a formatting function, a la this thread: round() in Python doesn't seem to be rounding properly

However, that only seems to work for rounding to the right of the decimal. Am I wrong? Is there another way to do this? Very frustrating trying to get the math right.

Thanks!

Community
  • 1
  • 1
MrDarkHorse
  • 11
  • 1
  • 3

1 Answers1

4

The problem is that 2e25 doesn't actually equal 20000000000000000000000000.

>>> 2e25 == 20000000000000000000000000
False
>>> 2e25 == 20000000000000001811939328
True

The float type doesn't have enough precision to represent such a large integer exactly. Unless you have a good reason for using floating-point values, use integers instead.

chepner
  • 497,756
  • 71
  • 530
  • 681