How to avoid extra digit being added in the addition of decimals in Python

Question:

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

Asked By: amol

||

Answers:

Just use the function round(number, ndigits)

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"))
Answered By: kosciej16

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))
Answered By: River
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.