To parse a float with 2 decimal places in JavaScript:
- Use the
parseFloat()
method to parse the string to a float point number. - Use the
toFixed()
method to format the floating point number to 2 decimal places. - The
toFixed()
method takes a number as input and returns a string representation of the number formatted to 2 decimal places.
const str1 = '2.567'
const res1 = parseFloat(str1).toFixed(2)
console.log(res1) // 2.57
const str2 = '5'
const res2 = parseFloat(str2).toFixed(2)
console.log(res2) // 5.00
const str3 = '4.5'
const res3 = parseFloat(str3).toFixed(2)
console.log(res3) // 4.50
We use the parseFloat()
method to convert the string into a floating point number.
Next, we called the toFixed()
method on the pointing point number, passing it 2
as the number of digits to appear after the decimal point. It rounds the number and pads the decimal places with zero if necessary.
Note that the toFixed()
method returns a string representing the pointing point number. If you need a number, as a result, call the parseFloat()
method again:
const str = '3.500'
const res = parseFloat(str).toFixed(2)
console.log(res) // 3.50
console.log(typeof res) // string
// Parse the string back to a number
const num = parseFloat(res)
console.log(num) // 3.5
console.log(typeof num) // number
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.