Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Round half to even implementation for float
#include <array>
#include <cmath>
#include <iostream>
float roundHalfToEven(float f)
{
const float r = round(f); // Result is round-half-away-from-zero
const float d = r - f; // Difference
// Result is not half, RHAFZ result same as RHTE
if ((d != 0.5f) && (d != -0.5f))
{
return r;
}
// Check if RHAFZ result is even, then RHAFZ result same as RHTE
if (fmod(r, 2.0f) == 0.0f)
{
return r;
}
// Switch to even value
return f - d;
}
int main()
{
const std::array<float, 8> fvals {{-5.5, -4.5, -3.5, -0.5, 0.5, 3.5, 4.5, 5.5}};
for (float f : fvals)
{
const float r = roundHalfToEven(f);
std::cout << "roundHalfToEven(" << f << "): " << r << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.