You can use the toFixed()
method to format a number to 2 decimal places in JavaScript. The toFixed()
method takes a number as input, representing the number of digits to appear after the decimal point, and returns a formatted string representing the given number.
const num1 = 12.865
const res1 = num1.toFixed(2)
console.log(res1) // 12.87
const num2 = 19
const res2 = num2.toFixed(2)
console.log(res2) // 19.00
In the above examples, we called the toFixed()
method on the number, passing it 2
as a parameter to format the number to 2 decimal places.
The only parameter toFixed()
takes is the number of digits to appear after the decimal point. The value must be between 0
and 100
inclusive. If this argument is skipped, it is treated as 0
. If you pass a value greater than 100
, a RangeError
is thrown:
const num1 = 17.8654553
const res1 = num1.toFixed()
console.log(res1) // 18
const num2 = 55.3469
const res2 = num2.toFixed(120)
console.log(res2)
// RangeError: toFixed() digits argument must be between 0 and 100
Using toFixed()
with negative numbers may produce unexpected results. You need to group the negative number expression to get a formatted string:
const res1 = -7.892.toFixed(2)
console.log(res1) // -7.89
console.log(typeof res1) // number --> ❌
const res2 = (-7.892).toFixed(2)
console.log(res2) // -7.89
console.log(typeof res2) // string --> ✅
If the number is wrapped in a string, you need to convert the string to a number first before calling the toFixed()
method:
const str = '22.567'
const res = parseFloat(str).toFixed(2)
console.log(res) // 22.57
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.