Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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.14

Getting a number

If you need a number rather than text, round with Math.round():

console.log(Math.round(3.14159 * 100) / 100);

Output:

3.14

The 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.5

Common 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.01

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.