How to round a number to two decimal places
Short answer
The toFixed() method returns a string with the required number of digits:
console.log((3.14159).toFixed(2));Output:
3.14Getting a number
If you need a number rather than text, round with Math.round():
console.log(Math.round(3.14159 * 100) / 100);Output:
3.14The difference between the two
toFixed() keeps trailing zeros, a number does not:
console.log((2.5).toFixed(2));
console.log(Math.round(2.5 * 100) / 100);Output:
2.50
2.5Common mistake
Numbers like 1.005 are stored a tiny bit lower than they look, so they round down. Adding Number.EPSILON fixes most such cases:
console.log(Math.round(1.005 * 100) / 100);
console.log(Math.round((1.005 + Number.EPSILON) * 100) / 100);Output:
1
1.01Functions used in this recipe
- Number.prototype.toFixed — Formats a number with a given number of decimal places.
- Math.round — Rounds a number to the nearest integer.
- Intl.NumberFormat — Formats numbers, currencies, percents and units by language rules.