Compare floats to three decimal places

后端 未结 5 2043
不思量自难忘°
不思量自难忘° 2021-01-14 03:44

I wanted to know what would be the fastest approach of comparing floats to three decimal places.Say I have something like this

float lhs = 2.567xxxx
float rh         


        
5条回答
  •  逝去的感伤
    2021-01-14 04:19

    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.)

提交回复
热议问题