How to Parse Float with 2 Decimal places in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20211 min read

banner

Photo by Luke Brugger

Parse Float with 2 Decimal places #

To parse a float with 2 decimal places, pass the number as a parameter to the parseFloat() function and call the toFixed(2) method on the result. The toFixed method will format the number to 2 decimal places and return the string representation.

index.js
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 a number, call the parseFloat method again.
index.js
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 every time you convert a string with trailing zeros to a number, they get removed.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee