Ken*_*Ken 5 javascript precision rounding
我需要使用JavaScript将十进制数舍入到六位,但我需要考虑旧版浏览器,所以我不能依赖于Number.toFixed
toExponential,toFixed和toPrecision的最大优点是它们是Mozilla中不支持的相当现代的构造,直到Firefox 1.5版(尽管IE支持自5.5版以来的方法).虽然使用这些方法最安全,但是如果您正在编写公共程序,那么旧版浏览器将会破坏,因此建议您提供自己的原型,以便为旧浏览器提供这些方法的功能.
我正在考虑使用类似的东西
Math.round(N*1000000)/1000000
Run Code Online (Sandbox Code Playgroud)
向旧版浏览器提供原型的最佳方法是什么?
Ser*_*sky 15
试试这个:
if (!Number.prototype.toFixed)
Number.prototype.toFixed = function(precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(this * power)/power);
}
Run Code Online (Sandbox Code Playgroud)