DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Gaussian/Banker's Rounding

01.27.2006
| 7481 views |
  • submit to reddit
        Gaussian rounding (aka Banker's rounding) rounds numbers in such a way as there is no upwards bias when rounding x.5. This minimises cumulative error in summing, averaging, &c. rounded numbers.

/**
 * Gaussian rounding (aka Banker's rounding) is a method of statistically
 * unbiased rounding. It ensures against bias when rounding at x.5 by
 * rounding x.5 towards the nearest even number. Regular rounding has a
 * built-in upwards bias.
 */
function gaussianRound(x) {
    var absolute = Math.abs(x);
    var sign     = x == 0 ? 0 : (x < 0 ? -1 : 1);
    var floored  = Math.floor(absolute);
    if (absolute - floored != 0.5) {
        return Math.round(absolute) * sign;
    }
    if (floored % 2 == 1) {
        // Closest even is up.
        return Math.ceil(absolute) * sign;
    }
    // Closest even is down.
    return floored * sign;
}

Thanks to Dennis W Jay for pointing out a bug in the code.