To put a stop to the onslaught of answers that are wrong because they allow rounding to alter the results, here is an answer that does not have the rounding problem, because it uses double
for the arithmetic:
trunc(1000. * lhs) == trunc(1000. * rhs);
This works because 1000.
has type double
, so the other operand is converted from float
to double
, and the multiplication is performed in the double
format. The product of 1000 with any float
value is exactly representable in double
, so there is no rounding error (assuming IEEE 754 32-bit and 64-bit binary floating-point). Then we use trunc
to compare the numbers up to the (original) third digit after the decimal point.
I hesitated to provide this answer because I am not sure it is what the OP really wants. Often when people come to Stack Overflow with a request for comparing “to three decimal places”, they have not entirely thought through the problem. A complete correct answer may have to wait until we have clarification.
Also, the above is for positive numbers only. If the values may be negative, then a prior test should be performed on their signs, and false
should be returned if they differ. (Otherwise, –.0009 would be reported as equal to +.0009.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…