Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Wil Stewart
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.
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.
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
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.