I know you should never compare floating point value using the == equality operator in .NET, but is it safe to do so if the two numbers were floored using Math.Floor?
I am working with a mapping program, and chunks of the map are stored in different “region” files. I can determine what region to retrieve by dividing the world coordinates by 16 and flooring the result, which gets me region coordinates.
I’m essentially asking whether or not two values that have the same whole number portion (e.g. 4.3 and 4.8) that are floored will be compared as equal using the == operator.
The general issue with floating point comparisons is that they can easily accrue rounding error. When you take a value like
1.2(which cannot be exactly represented as a decimal) multiply it by100and compare it for equality to120. The recommendation is to always compare the difference like so:The
Math.Floor()operation, however, always results in an integer value. That is to say that any fractional values will be truncated, and the exact integer value will be left.So, if your semantics really are to use a floor, you are safe.
However, if you are really trying to round, then use
Math.Round()instead.