Rounding issue in Math.round() & .toFixed()

前端 未结 7 1093
半阙折子戏
半阙折子戏 2020-12-10 16:58

I used below two methods :

Number.prototype.myRound = function (decimalPlaces) {
    var multiplier = Math.pow(10, decimalPlaces);

    return (Math.round(th         


        
相关标签:
7条回答
  • 2020-12-10 17:28

    This method will give very correct round result.

    function RoundNum(num, length) { 
        var number = Math.round(num * Math.pow(10, length)) / Math.pow(10, length);
        return number;
    }
    

    Just call this method.

    alert(RoundNum(192.168,2));
    
    0 讨论(0)
  • 2020-12-10 17:28

    round() will do the trick.Try This:

    var v= Math.round(239.575 * 100) / 100;
    alert(v);
    

    Working FIddle

    0 讨论(0)
  • 2020-12-10 17:32

    In my software I use this:

    (require DecimalJS)

    Number.prototype.toFixed = function(fixed) {
        return (new Decimal(Number(this))).toFixed(parseFloat(fixed) || 
    0);
    };
    
    
    var x = 1.005;
    console.log( x.toFixed(2) ); //1.01
    
    0 讨论(0)
  • 2020-12-10 17:38

    The problem is probably floating point inaccuracy, thus you might get different results in different cases (different gathering of a number, different browsers etc.).

    See also this: toFixed(2) rounds "x.525" inconsistently?

    0 讨论(0)
  • 2020-12-10 17:46
    function bestRound(val, decimals){
        decimals = decimals || 2;
        var multiplier = Math.pow(10, decimals)
        return Math.round((val * multiplier ).toFixed(decimals)) / multiplier;
      }
    
    bestRound(239.575 - 239.5)   0.08
    bestRound(239.575)         239.58
    bestRound(239.525)         239.53
    bestRound(1.005)             1.01
    
    0 讨论(0)
  • 2020-12-10 17:49

    Internally, 239.575 cannot be represented exactly. In binary, 0.575 would be something like 1/2 + 1/16 + 1/128 + 1/256 + ....

    It just so happens that, represented in binary, the result is slightly less than 239.575. Therefore, Math.round rounds down.

    To demonstrate, try this:

    alert(239.575 - 239.5)
    

    You would expect the result to be 0.075, but instead you get 0.07499999999998863.

    0 讨论(0)
提交回复
热议问题