How to Parse Float with Two Decimal Places in JavaScript?
Last Updated :
05 Sep, 2024
JavaScript provides an inbuilt parseFloat() method to parse a string and returns a floating-point number.
Below are the approaches to parse float to two decimal places in JavaScript:
Approach 1: Using parseFloat() Method
The parseFloat() method converts a string to a floating-point number. If the string isn’t numeric, it returns NaN. To limit the number to two decimal places, use toFixed(2), which rounds the result.
Example 1: In this example the parseFloat converts strings to floating-point numbers. toFixed(2) rounds the number to 2 decimal places, returning a string. num1 shows the full precision, while num2 is rounded.
JavaScript
let num1 = parseFloat("10.547892")
let num2 = parseFloat("10.547892").toFixed(2)
console.log("Without using toFixed() method: ",num1);
console.log("Using toFixed() method: ", num2);
OutputWithout using toFixed() method: 10.547892
Using toFixed() method: 10.55
Approach 2: Using Custom parseFloat Method
The custom parseFloat method converts a number to a string, slices it to retain only the desired decimal places, and then converts it back to a number. This method ensures no rounding, preserving exact precision.
Example: In this example, the ParseFloat converts a string to a number with specified decimal places. It slices the string up to the desired decimal precision and then converts it back to a number.
JavaScript
function ParseFloat(str,val) {
str = str.toString();
str = str.slice(0, (str.indexOf(".")) + val + 1);
return Number(str);
}
console.log(ParseFloat("10.547892",2))
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.