Reliable JS rounding numbers with toFixed(2) of a 3 decimal number

后端 未结 5 1869
野的像风
野的像风 2020-12-11 06:54

I am simply trying to round up 1.275.toFixed(2) and I was expecting a return of 1.28, rather than 1.27.

Using various calculators and t

5条回答
  •  粉色の甜心
    2020-12-11 07:09

    According to Robby's answer, MDN describes a reliable rounding implementation, therefore I stripped it down to the following snippet to solve my issue of rounding a 3 decimal number of 1.275 to 1.28. Tested in FF4, Chrome 55 and Safari 10.0.3 on MacOS

    function decimalAdjust(c,a,b){if("undefined"===typeof b||0===+b)return Math[c](a);a=+a;b=+b;if(isNaN(a)||"number"!==typeof b||0!==b%1)return NaN;a=a.toString().split("e");a=Math[c](+(a[0]+"e"+(a[1]?+a[1]-b:-b)));a=a.toString().split("e");return+(a[0]+"e"+(a[1]?+a[1]+b:b))}Math.round10||(Math.round10=function(c,a){return decimalAdjust("round",c,a)});
    
    Math.round10(1.275, -2);
    

提交回复
热议问题