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?
Try this:
Another option is ( which doesn't convert to a string unnecessarily, and also corrects the miscalculation of (162.295).toFixed(2) to 162.29 ( should be 162.30 )).
Edit: Upon trying this specific incarnation,
this*=Math.pow(10, precision||0)
creates an error invalid left-hand assignment. So gave the this keyword the variablea
. It would also help if I closed my functions ^_^;;I think Firefox 1.5 and IE 5 are pretty much no longer used, or by a very minor quantity of people.
It is a bit like coding to support Netscape Navigator... :-)
Unless some other major browser (Opera? Safari? unlikely...) doesn't support this, or if your Web logs show lot of legacy browser use, you can probably just use these methods.
Sometime, we have to move on. ^_^
[EDIT] Works fine on Opera 9.50 and Safari 3.1
The article you reference is a year and half ago, an eternity in IT industry... I think that, unlike IE users, Firefox users often go to the latest version.
Try this:
From Bytes website, this function is almost the same than Serge llinsky's: