Borislav Hadzhiev
Fri Oct 22 2021·2 min read
Photo by Luke Brugger
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.
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:
toFixed
method returns a string. If you need the result to be a 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 every time you convert a string with trailing zeros to a number, they get removed.