0

print(37.4<(32.0+5.0+0.2+0.2)) This statement gives a True result but I need it should give me a False as the addition of the numbers (32.0+5.0+0.2+0.2) is precisely the same as 37.4 but here it gives the following result 37.400000000000006 for this equation (32.0+5.0+0.2+0.2). Hence, I am getting a True result rather False one.

I am new to python so don't know how to deal with it.

Many thanks

amol
  • 1,497
  • 5
  • 17
  • 26
  • `(32.0+5.0+0.2+0.2)` indeed results in `37.400000000000006` in many programming languages. Even `0.1+0.2` results in `0.30000000000000004`. Refer to https://stackoverflow.com/questions/588004/is-floating-point-math-broken . And this site shows the behaviors of many different programming languages: https://0.30000000000000004.com/ – qrsngky Apr 03 '23 at 09:48
  • In this case, you could also multiply with 10 and compare the int values. – Mike Scotty Apr 03 '23 at 09:50
  • Plenty of Python solutions presented in answers to the linked duplicate. – Robby Cornelissen Apr 03 '23 at 09:51

3 Answers3

1

Just use the function round(number, ndigits)

TheEngineerProgrammer
  • 1,282
  • 1
  • 4
  • 9
0

I suggest to use decimals

from decimal import Decimal

print(Decimal("37.4") < Decimal("32.0") + Decimal("5.0") + Decimal("0.2") + Decimal("0.2"))
kosciej16
  • 6,294
  • 1
  • 18
  • 29
0

Just use round().

For example, if you want to round the number to 2 digits, do this:

round((32.0+5.0+0.2+0.2), 2)

And to answer your issue:

print(37.4<round((32.0+5.0+0.2+0.2), 2))
River
  • 47
  • 7