Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 589
Ken Avatar asked Dec 03 '08 13:12

Ken


1 Answers

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);
    }
like image 73
Sergey Ilinsky Avatar answered Oct 21 '22 15:10

Sergey Ilinsky