I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1 1.00
1.341 1.34
1.345 1.35
I have been using this:
parseFloat(num).toFixed(2);
But it's displaying 1
as 1
, rather than 1.00
.
For the most accurate rounding, create this function:
and use it to round to 2 decimal places:
Thanks to Razu, this article, and MDN's Math.round reference.
Is this what you mean?
I do like:
Round the number with 2 decimal points, then make sure to parse it with
parseFloat()
to return Number, not String unless you don't care if it is String or Number.For modern browsers, use
toLocaleString
:Specify a locale tag as first parameter to control the decimal separator. For a dot, use for example English U.S. locale:
which gives:
Most countries in Europe use a comma as decimal separator, so if you for example use Swedish/Sweden locale:
it will give:
This works fine in FF4:
Live Demo
Note that it will round to 2 decimal places, so the input
1.346
will return1.35
.Where specific formatting is required, you should write your own routine or use a library function that does what you need. The basic ECMAScript functionality is usually insufficient for displaying formatted numbers.
A thorough explanation of rounding and formatting is here: http://www.merlyn.demon.co.uk/js-round.htm#RiJAs a general rule, rounding and formatting should only be peformed as a last step before output. Doing so earlier may introduce unexpectedly large errors and destroy the formatting.