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
.
This answer will fail if
value = 1.005
.As a better solution, the rounding problem can be avoided by using numbers represented in exponential notation:
Credit: Rounding Decimals in JavaScript
If you're already using jQuery, you could look at using the jQuery Number Format plugin.
The plugin can return formatted numbers as a string, you can set decimal, and thousands separators, and you can choose the number of decimals to show.
You can also get jQuery Number Format from GitHub.