Table of Contents
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:
JAVASCRIPTconst 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:
JAVASCRIPTconst string = "123.45";
const number = parseFloat(string);
console.log(number);
console.log(typeof number);
BASH123.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:
JAVASCRIPTconst string = "123.456";
const number = parseFloat(string);
const fixedString = number.toFixed(2);
console.log(fixedString);
console.log(typeof fixedString);
BASH123.456
string
Now all we need to do is take this fixedString and once again convert it back to a float:
JAVASCRIPTconst string = "123.456";
const number = parseFloat(string);
const fixedString = number.toFixed(2);
const numberAgain = parseFloat(fixedString);
console.log(numberAgain);
console.log(typeof numberAgain);
BASH123.46
number
We can also wrap this into a nice function that we can call:
JAVASCRIPTconst 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);
BASH123.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!
Getting Started with TypeScript
How to Install Node on Windows, macOS and Linux
Getting Started with Svelte
Getting Started with Express
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
Getting Started with Deno
How to deploy an Express app using Docker
Learn how to use v-model with a custom Vue component
Getting User Location using JavaScript's Geolocation API
Using Push.js to Display Web Browser Notifications
Using Axios to Pull Data from a REST API
