Gaussian/banker's rounding in JavaScript

后端 未结 6 1663
天涯浪人
天涯浪人 2020-11-27 02:51

I have been using Math.Round(myNumber, MidpointRounding.ToEven) in C# to do my server-side rounding, however, the user needs to know \'live\' what the result of

6条回答
  •  醉话见心
    2020-11-27 03:22

    That's a great solution from @soegaard. Here is a small change that makes it work for decimal points:

    bankers_round(n:number, d:number=0) {
        var x = n * Math.pow(10, d);
        var r = Math.round(x);
        var br = (((((x>0)?x:(-x))%1)===0.5)?(((0===(r%2)))?r:(r-1)):r);
        return br / Math.pow(10, d);
    }
    

    And while at it - here are some tests:

    console.log(" 1.5 -> 2 : ", bankers_round(1.5) );
    console.log(" 2.5 -> 2 : ", bankers_round(2.5) );
    console.log(" 1.535 -> 1.54 : ", bankers_round(1.535, 2) );
    console.log(" 1.525 -> 1.52 : ", bankers_round(1.525, 2) );
    
    console.log(" 0.5 -> 0 : ", bankers_round(0.5) );
    console.log(" 1.5 -> 2 : ", bankers_round(1.5) );
    console.log(" 0.4 -> 0 : ", bankers_round(0.4) );
    console.log(" 0.6 -> 1 : ", bankers_round(0.6) );
    console.log(" 1.4 -> 1 : ", bankers_round(1.4) );
    console.log(" 1.6 -> 2 : ", bankers_round(1.6) );
    
    console.log(" 23.5 -> 24 : ", bankers_round(23.5) );
    console.log(" 24.5 -> 24 : ", bankers_round(24.5) );
    console.log(" -23.5 -> -24 : ", bankers_round(-23.5) );
    console.log(" -24.5 -> -24 : ", bankers_round(-24.5) );
    

提交回复
热议问题