logo To Foot
© J R Stockton, ≥ 2009-04-29

JavaScript Rounding 2.

No-Frame * Framed Index * Frame This
Links within this site :-

See "About This JavaScript Site" in JavaScript Index and Introduction.

Formatting a Number to a Decimal String

Using the Native Converter, Indirectly

Defective Conversions to String

To convert a signed number X, |X|<1019, to a string with 2 decimal places, having trailing zeroes as needed (compare entry in the c.l.j. FAQ, ≤2001-01-22) :-

or

N.B. for each, "1.5555" gives "1.56", "0.5555" gives ".56"; BUT "0.0555" gives ".6", "0.0055" gives ".1", "0.0033" gives ".0", which are not all correct.


To N decimal places (|X|<1021-N) :-

N.B. as above.


To N decimal places, or e-format :-

N.B. as above.

Satisfactory Conversions to String

Unsigned, to 2 decimal places, 0≤X<1021, correctly :-

Unsigned, to 2 decimal places, 0≤X<1019, correctly :-


Unsigned, to N decimal places, 0≤X<1021-N, correctly :-


Unsigned, to at least M digits point N decimal places, 0≤X<1021-N, correctly :-


Unsigned, to N decimal places, or e-format :-


Signed, to 2 or N decimal places, 0≤|X|<1021-N, correctly :-

N.B. Others in pink? above can be corrected similarly, by while.

Another Conversion to String

Signed, to N decimal places, ?≤|X|<1021, correctly? :-

N.B. goes to e-format for some small values ...

Other Good? Conversions to String

Another signed method, for two decimal places :-


Another for unsigned non-vast currency :-


Another (after Evertjan, modified) for unsigned non-vast currency :-

And, for signed non-vast currency (0.00 may be signed) :-

0r (0.00 never signed) :-


Another (seemingly OK, after Ivo) :-


Another (seemingly OK; much as posted by DA in m.p.s.j 20030306).


A direct implementation by DA of toFixed is in Rounding 1.


Another (seemingly OK) :-


Another (seemingly OK), after Targa :-


From FAQ de.comp.lang.javascript Aug 2004 :-


From FAQ de.comp.lang.javascript Aug 2004 :-



After RobG.


Modified from SAM.


Another, by me.


Note how some of those routines give improper formats for large numbers.

Should any more of those be made Methods of String or Number?

To allow for any browsers that cannot handle previously-used Number("1e"+N), one can use (X*'100000000000000000000'.substring(0,N+1)) where the literal number has N or more zeroes for the largest N. Or, for the common case of N=2, just write 100. Or use Math.pow(10, N).



JavaScript Rounding   0, 1, 3.
Home Page
Mail: no HTML
© Dr J R Stockton, near London, UK.
All Rights Reserved.
These pages are tested mainly with MS IE 7 and W3's Tidy.
This site, http://www.merlyn.demon.co.uk/, is maintained by me.
Head.