javascript - 如何在 JavaScript 中为 Number.toFixed 编写原型(prototype)?

标签 javascript rounding precision

我需要使用 JavaScript 将小数四舍五入到六位,但我需要考虑旧版浏览器,所以我 can't rely on Number.toFixed

The big catch with toExponential, toFixed, and toPrecision is that they are fairly modern constructs not supported in Mozilla until Firefox version 1.5 (although IE supported the methods since version 5.5). While it's mostly safe to use these methods, older browsers WILL break so if you are writing a public program it's recommended you provide your own prototypes to provide functionality for these methods for older browser.

我正在考虑使用类似的东西

Math.round(N*1000000)/1000000

向旧版浏览器提供原型(prototype)的最佳方法是什么?

最佳答案

试试这个:

if (!Number.prototype.toFixed)

    Number.prototype.toFixed = function(precision) {
        var power = Math.pow(10, precision || 0);
        return String(Math.round(this * power)/power);
    }

关于javascript - 如何在 JavaScript 中为 Number.toFixed 编写原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/337112/

相关文章:

python - 为什么当我从数组中减去时没有任何反应?如何从 python 中获得更好的精度?

javascript - HTML5 使用 createMediaElementSource() 缓冲和播放音频

javascript - 如何动态调整vue组件中的文本大小

javascript - 当前 URL hashchange 事件将新哈希附加到目标 URL 并链接到它

javascript - Javascript toFixed() 方法中的舍入

swift - 如何用 E 对 double 值进行四舍五入

javascript - 为什么使用 Knockout.js 时数据没有出现在 HTML 字段中

Ruby:为什么 1.025.round(2) 四舍五入为 1.02?

sql - 如何查询精度过高的美元金额?

math - float 学有问题吗?