Let a = 1.11114 b = 1.11118
When I compare these two variables using the code below
if b <= a
I want the comparison to be done only up to 4 decimal places, such that a = b. Can anyone help me with an efficient code? Thank you!
Let a = 1.11114 b = 1.11118
When I compare these two variables using the code below
if b <= a
I want the comparison to be done only up to 4 decimal places, such that a = b. Can anyone help me with an efficient code? Thank you!
To avoid rounding, you can multiply the number by power of 10 to cast to integer up to the decimal place you want to consider (to truncate the decimal part), and then divide by the same power to obtain the truncated float:
n = 4 # number of decimal digits you want to consider
a_truncated = int(a * 10**n)/10**n
See also Python setting Decimal Place range without rounding?
Possible duplicate of Truncate to three decimals in Python
Extract x digits with the power of 10^x and then divide by the same:
>>> import math
>>> def truncate(number, digits) -> float:
... stepper = 10.0 ** digits
... return math.trunc(stepper * number) / stepper
>>> a
1.11114
>>> b
1.11118
>>> truncate(a,4) == truncate(b,4)
True
Solution by @Erwin Mayer
You can look at whether their differences is close to 0 with an absolute tolerance of 1e-4 with math.isclose
:
>>> import math
>>> math.isclose(a - b, 0, abs_tol=1e-4)
True
Use round() in-built function -
a = round(a,4) # 4 is no. of digits you want
b = round(b,4)
if a >= b :
... # Do stuff