I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1
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:
Number(Math.round(1.005+'e2')+'e-2'); // 1.01
Cleaner code as suggested by @Kon, and the original author:
Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)
You may add toFixed()
at the end to retain the decimal point e.g: 1.00
but note that it will return as string.
Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)
Credit: Rounding Decimals in JavaScript