Gaussian/banker's rounding in JavaScript

后端 未结 6 1647
天涯浪人
天涯浪人 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:27

    The accepted answer does round to a given number of places. In the process it calls toFixed which converts the number to a string. Since this is expensive, I offer the solution below. It rounds a number ending in 0.5 to the nearest even number. It does not handle rounding to an arbitrary number of places.

    function even_p(n){
      return (0===(n%2));
    };
    
    function bankers_round(x){
        var r = Math.round(x);
        return (((((x>0)?x:(-x))%1)===0.5)?((even_p(r))?r:(r-1)):r);
    };
    

提交回复
热议问题