3 ms·
Doesn't the modulus function avoid most of the issues, here? float RoundToNearestWholeNumber(float f) { if (double.IsNanOrInfinity(f)) return f;
by Strilanc 13y ago
Doesn't the modulus function avoid most of the issues, here?
float RoundToNearestWholeNumber(float f) {
if (double.IsNanOrInfinity(f)) return f;
if (f < 0) return -RoundToNearestWholeNumber(-f);
// make sure we're working with a consistent value
float v = DiscardExtraPrecision(f);
// the fractional part is guaranteed to be representable
float r = v % 1;
// largest whole value up to v (the floor)
float w = v - r;
// switch to the ceiling if in the upper half
if (r > 0.5) return w + 1;
return w;
}
Feel free to disillusion me.