How to Parse Float to 2 Decimal Places in JavaScript
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!
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- How to deploy an Express app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React