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

前端 未结 7 1120
半阙折子戏
半阙折子戏 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: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.

提交回复
热议问题