Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

rounding - How to write a prototype for Number.toFixed in JavaScript?

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

if (!Number.prototype.toFixed)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...