Can you help me with this task? I have a problem with rounding numbers to several decimal places.
This is my code:
function going(n) {
let x = 1 / factorial(n);
let y = 0;
for(let i = 1; i <= n; i++){
y += factorial(i);
}
return (x*y);
}
function factorial(n) {
let br = 1;
for(let i = 1; i <= n; i++){
br *= i;
}
return br;
}
For n equal to 6 the result should be 1.2125 however I get 1.2125000000000001.
1.0000989217538616 will be truncated to 1.000098
1.2125000000000001 will be truncated to 1.2125
How do I solve it? These are the required results for the other values of the variable n.
(going(5), 1.275)
(going(6), 1.2125)
(going(7), 1.173214)
For each of these examples, the number of digits to be rounded is different. Note the return value should be a number and not a string!
I tried to solve the problem through these functions but it didn't work:
toExponential()
toFixed()
toPrecision() and Number
parseFloat(), parseInt()