Round a Number to 3 Decimal Places in JavaScript


Borislav Hadzhiev

Sat Oct 23 20212 min read


Photo by Wil Stewart

Round a Number to 3 Decimal Places #

Use the toFixed() method to round a number to 3 decimal places, e.g. num.toFixed(3). The toFixed method formats a number to a specified number of decimal places and rounds the number if necessary.

const num1 = 7.456677; const result1 = num1.toFixed(3); console.log(result1); // 👉️ 7.457 console.log(typeof result1); // 👉️ string // 👇️ if the value is a string // call parseFloat to convert it to a number first const str1 = '7.456677'; const result2 = parseFloat(str1).toFixed(3); console.log(result2); // 👉️ 5.457 console.log(typeof result2); // 👉️ string // 👇️ Convert string back to a number const num2 = 7.79999999; const result3 = Number(num2.toFixed(3)); console.log(result3); // 👉️ 7.8 console.log(typeof result3); // 👉️ number

In the first example, we used the Number.toFixed method to round a number to 3 decimal places.

The only parameter the method takes is the number of digits that should appear after the decimal point.

The toFixed method returns a string representation of the number.

In the second example, we have a string that is a valid number. We had to convert it to a number using the parseFloat function because the toFixed method can only be called on numbers.

In the third example, we used the Number object to turn the string that the toFixed method returns into a number.

However, notice that 2 trailing zeros were removed. When you convert a string with trailing zeros to a number in JavaScript, none of the trailing zeros are kept.

The number 7.000 is the same as 7, so the trailing zeros get dropped when the value is converted to a number.

console.log(7.000 === 7); // 👉️ true
Floating point numbers don't represent all decimals precisely in binary, which can lead to inconsistent results.
console.log(0.1 + 0.2 === 0.3); // 👉️ false

The sum of 0.1 and 0.2 is actually equal to 0.30000000000000004 instead of 0.3. This is because the binary floating-point format cannot accurately represent numbers like 0.1 or 0.2.

The code gets rounded to the nearest number, resulting in a rounding error.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.