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