如何在JavaScript中编写Number.toFixed的原型? [英] How to write a prototype for Number.toFixed in JavaScript?

查看:157
本文介绍了如何在JavaScript中编写Number.toFixed的原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用JavaScript将十进制数字舍入到六个位置,但我需要考虑旧版浏览器,以便 can不依赖于Number.toFixed

I need to round decimal numbers to six places using JavaScript, but I need to consider legacy browsers so I can't rely on Number.toFixed


toExponential,toFixed和toPrecision的最大优点是它们是相当现代的构造在Firefox 1.5版之前不支持Mozilla(虽然IE支持自5.5版以来的方法)。虽然使用这些方法最安全,但是如果您正在编写公共程序,旧的浏览器会破坏,建议您提供自己的原型,为旧浏览器提供这些方法的功能。

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.

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

I'm considering using something like

Math.round(N*1000000)/1000000

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

What is the best method for providing this a prototype to older browsers?

推荐答案

试试这个:

if (!Number.prototype.toFixed)

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

这篇关于如何在JavaScript中编写Number.toFixed的原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆