0

Quick summary - I was running a piece of code(in React application) where I am summing up decimal values entered by a user. One of the conditions to move to next page is if the sum equals 100

Problem - In one case, the sum of all values (a+b+c+d+e+f) is being computed to 99.99999999999997 even though the summation(over a calculator) is 100. But when I change the summation order to a+d+e+f+b+c, the sum is correctly computed to 100.

Please find below code samples -

Wrong summation -

const result = [15+10.4+1.9+1.9+4.9+2.8+6.8+2+4.9+2.8+2.5+2.8+4.8+6.5+15+15].reduce((sum, val) => {return sum+val}, 0)
console.log(result) //99.99999999999997

Correct summation -

const result = [15+10.4+4.9+2.8+6.8+2+4.9+2.8+2.5+2.8+4.8+6.5+15+15+1.9+1.9].reduce((sum, val) => {return sum+val}, 0)
console.log(result) //100

Questions -

  1. How does JavaScript engine compute?
  2. How to compute to 100 always (without using ceil, floor or round methods because Math.round(99.6) is also equal to 100.
Bijoy valappil
  • 139
  • 2
  • 12
  • You will need to do rounding - just don't round to whole integers, but round to a tenth if that's the precision you want for your numbers. `Math.round(result * 10) == 1000` – Bergi Sep 19 '22 at 10:40

0 Answers0