'Javascript | floating point numbers
When assigning 2 variables with decimal point numbers and calculating the sum of both of them when using console.log() to return the result if they equal the whole number they return it without the decimal point.
For example
let num1 = 2.2;
let num2 = 2.8;
console.log(num1 + num2 )
returns 5 when I require 5.0 to be returned.
I've tried toFixed(1) but the test requires various numbers to be returned
For example
let num1 = 2.22
let num2 = 2.71
console.log((num1 + num2)toFixed(1))
returns 4.9 when I require 4.93
Is there a way I can assign the variable a floating-point decimal and keep its status even in the return value is a whole number?
Solution 1:[1]
function add(num1, num2) {
const num1PointLength = String(num1).split(".")[1]?.length || 0;
const num2PointLength = String(num2).split(".")[1]?.length || 0;
return (num1 + num2).toFixed(num1PointLength > num2PointLength ? num1PointLength : num2PointLength);
}
let num1 = 2.2;
let num2 = 2.8;
console.log(add(num1, num2));
Solution 2:[2]
toFixed()-> this method rounds the string to a specified number of decimals.If the number of decimals are higher than in the number, zeros are added.
let num1 = 2.2
let num2 = 2.8
console.log((num1 + num2).toFixed(1))
returns=> 5.0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dangerousmanleesanghyeon |
| Solution 2 | Siddharth Agrawal |
