Parse float with 2 decimal places in JavaScript

To parse a float with 2 decimal places in JavaScript:

  1. Use the parseFloat() method to parse the string to a float point number.
  2. Use the toFixed() method to format the floating point number to 2 decimal places.
  3. 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.