最近發現JS當中toFixed()方法存在一些問題。采用toFixed()方法時,規則并不是標準的“四舍五入”。而且不同的瀏覽器會有不同的結果,所以為了滿足正確的運算,需要對toFixed重寫。在瀏覽了各大論壇后,有這么一種比較簡單的方法:<script>Number.prototype.toFixed = function (exponent) {
return parseInt(this * Math.pow(10, exponent) + 0.5) / Math.pow(10, exponent);
}</script>原理就不解釋了,來不及了。這個方法在正數情況下是可行的,但是對于負數還是會有偏差。例如:document.write((-0.050).toFixed(2));在Chrome下會輸出為-0.04;我覺得問題出現在+0.5那里,但是不知道咋改。請大神指點一二。另外,如果有更好的辦法,還請不吝賜教,謝謝。想了下……貌似這樣可以的:Number.prototype.toFixed = function (exponent) {
if(this>0){ return parseInt(this * Math.pow(10, exponent) + 0.5) / Math.pow(10, exponent);
}else{ return parseInt(this * Math.pow(10, exponent) - 0.5) / Math.pow(10, exponent);
}
}那么……還有更好的辦法嘛?
關于.toFixed()的重寫
BIG陽
2018-10-17 11:14:51