Add float numbers using JavaScript
Given two or more numbers the task is to get the float addition in the desired format with the help of JavaScript.
There are two methods to solve this problem which are discussed below:
Using parseFloat() and toFixed() method
- Given two or more numbers, to sum up the float numbers.
- Use parseFloat() and toFixed() method to format the output accordingly.
let val = parseFloat('2.3') + parseFloat('2.4');
console.log("2.3 + 2.4 = " + val);
function parse() {
console.log("2.3 + 2.4 = "
+ (parseFloat('2.3') +
parseFloat('2.4')).toFixed(2));
}
parse()
Output
2.3 + 2.4 = 4.699999999999999 2.3 + 2.4 = 4.70
Using parseFloat() and Math.round() method
- Given two or more numbers, to sum up the float numbers.
- Use parseFloat() and Math.round() method to get the desired output.
let val = parseFloat('2.3') + parseFloat('2.4');
console.log("2.3 + 2.4 = " + val);
function parse() {
console.log("2.3 + 2.4 = " +
Math.round((parseFloat('2.3')
+ parseFloat('2.4')) * 100) / 100);
}
parse()
Output
2.3 + 2.4 = 4.699999999999999 2.3 + 2.4 = 4.7
Using Number() and Intl.NumberFormat method
Given two or more numbers, to sum up the float numbers:
- Use Number() to convert strings to floating-point numbers.
- Use Intl.NumberFormat to format the output accordingly.
let val = Number('2.3') + Number('2.4');
console.log("2.3 + 2.4 = " + val);
function parse() {
let sum = Number('2.3') + Number('2.4');
let formattedSum = new Intl.NumberFormat('en-US',
{ minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(sum);
console.log("2.3 + 2.4 = " + formattedSum);
}
parse();
Output
2.3 + 2.4 = 4.699999999999999 2.3 + 2.4 = 4.70