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
.
You are not giving us the whole picture.
javascript:alert(parseFloat(1).toFixed(2))
shows 1.00 in my browsers when I paste it int0 the location bar. However if you do something to it afterwards, it will revert.Extend Math object with precision method
A much more generic solution for rounding to N places
I had to decide between the parseFloat() and Number() conversions before I could make toFixed() call. Here's an example of a number formatting post-capturing user input.
HTML:
Event handler:
The above code will result in TypeError exception. Note that although the html input type is "number", the user input is actually a "string" data type. However, toFixed() function may only be invoked on an object that is a Number.
My final code would look as follows:
The reason I favor to cast with Number() vs. parseFloat() is because I don't have to perform an extra validation neither for an empty input string, nor NaN value. The Number() function would automatically handle an empty string and covert it to zero.
This is how I solve my problem: