How to Parse Float with 2 Decimal places in JavaScript


Borislav Hadzhiev

Last updated: Jul 25, 2022


Photo from Unsplash

Parse Float with 2 Decimal places #

To parse a float with 2 decimal places:

  1. Pass the float to the parseFloat() function.
  2. Use the toFixed() method to format the float to 2 decimal places.
  3. The toFixed method will return a string representation of the number formatted to 2 decimal places.
const ex1 = parseFloat('3.00').toFixed(2); console.log(ex1); // 👉️ 3.00 console.log(typeof ex1); // 👉️ string const ex2 = parseFloat(3).toFixed(2); console.log(ex2); // 👉️ 3.00 console.log(typeof ex2); // 👉️ string const ex3 = parseFloat('3.1').toFixed(2); console.log(ex3); // 👉️ 3.10 const ex4 = parseFloat('3.509').toFixed(2); console.log(ex4); // 👉️ 3.51 const ex5 = parseFloat('3.505').toFixed(2); console.log(ex5); // 👉️ 3.50

We used the parseFloat function to parse a string to a floating-point number.

The next step is to call the toFixed method on the number, passing it 2 as a parameter.

The only parameter the toFixed method takes is how many digits we want to appear after the decimal point.

The toFixed method:

  • rounds the number if necessary
  • pads the decimal places with zeros if necessary
Note that the toFixed method returns a string. If you need the result to be of type number, call the parseFloat method again.
const str = parseFloat('3.3').toFixed(2); console.log(str); // 👉️ 3.30 console.log(typeof str); // 👉️ string const num = parseFloat(str); console.log(num); // 👉️ 3.3 console.log(typeof num); // 👉️ number

Note that we don't have a trailing zero after we converted the string to a number.

You can't have numbers with trailing zeros in JavaScript, because the language doesn't keep insignificant trailing zeros around.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.