0

So the question is in the title. Here are some more details:

code:

a=0.975
print(round(a,2))
print(round(a*100)/100)

a=-0.975
print(round(a,2))
print(round(a*100)/100)

a=1.975
print(round(a,2))
print(round(a*100)/100)

a=-1.975
print(round(a,2))
print(round(a*100)/100)

The printed output is:

0.97
0.98
-0.97
-0.98
1.98
1.98
-1.98
-1.98

I guess there is something going on with floating point error and how round() handles float numbers? It seems to be the case between -1 and 1. Probably round() is shifting the floating point and creating a number with more digits after the 5?

Can someone explain, whether there is a way to avoid this?

dalleaux
  • 527
  • 5
  • 11
  • 3
    Duplicate of [Python rounding error with float numbers](https://stackoverflow.com/questions/5997027/python-rounding-error-with-float-numbers). See also https://docs.python.org/3/tutorial/floatingpoint.html – Guy Incognito Feb 15 '23 at 09:53
  • 1
    The value of the first `a` is actually 0.97499999999999997779553950749686919152736663818359375. The others have the same issue. – molbdnilo Feb 15 '23 at 11:02

1 Answers1

2

This is a known isue with floating points with Python. You can see the real value Python is storing as decimal point with the decimal library:

from decimal import Decimal

print(Decimal(0.975)

To avoid this issue you can just use de decimal library before the round operation.

from decimal import Decimal

a = 0.975
print(float(round(Decimal(str(a)),2)))

This will print the desired 0.98 result.

Here you have the Decimal library documentation: https://docs.python.org/3/library/decimal.html

kithuto
  • 455
  • 2
  • 11