How to Parse Float to 2 Decimal Places in JavaScript

Updated onbyAlan Morel
How to Parse Float to 2 Decimal Places in JavaScript

Working with numbers in JavaScript can sometimes be difficult due to the fact that there are many different ways to represent numbers in JavaScript.

When you are given a string, especially one that represents money, you'll want to be able to parse it as a float to two decimal places.

In this post, we'll learn how to parse a string as a float to two decimal places in JavaScript.

How to parse a string as a float to two decimal places

To begin, let's start off with an example string:

const string = "123.45";

To parse a string as a float to two decimal places, we first must convert the string into a number.

To do this, you can use the parseFloat function:

const string = "123.45";

const number = parseFloat(string);

console.log(number);
console.log(typeof number);
123.45
number

Now this works, however if the string originally included, let's say, 3 decimal places, we have to use toFixed to limit that:

const string = "123.456";

const number = parseFloat(string);
const fixedString = number.toFixed(2);

console.log(fixedString);
console.log(typeof fixedString);
123.456
string

Now all we need to do is take this fixedString and once again convert it back to a float:

const string = "123.456";

const number = parseFloat(string);
const fixedString = number.toFixed(2);
const numberAgain = parseFloat(fixedString);

console.log(numberAgain);
console.log(typeof numberAgain);
123.46
number

We can also wrap this into a nice function that we can call:

const string = "123.456";

const parseToTwoDecimalPlaces = (string) => {
    const fixedString = parseFloat(string).toFixed(2);
    return parseFloat(fixedString);
}

const number = parseToTwoDecimalPlaces(string);

console.log(number);
console.log(typeof number);
123.46
number

And there you have your two decimal places number!

Conclusion

In this post, we looked at how to convert a string to a float with two decimal places.

All you need to do is convert the string to a float, use the toFixed function to limit the decimal places, and then convert the string back to a float.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.