0

how to get exact sum of rounded numbers

1) Math.round( ( 100/3 + Number.EPSILON ) * 100 ) / 100  // 3.33

2) Math.round( ( 100/3 + Number.EPSILON ) * 100 ) / 100 *3 // 99.99 

how to get 100 as sum if we add all the rounded numbers ?

Hithesh kumar
  • 1,008
  • 9
  • 25
  • You can't. Rounding drops or alters digits and there is no magical store that secretly keeps the original. If you need the original, then store the original. – Peter B Jul 22 '21 at 09:37
  • 1
    [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/q/1458633) – VLAZ Jul 22 '21 at 09:37
  • 1
    Some numbers just can't be represented in the binary floating point format used by JavaScript (and most other languages). Although thirds are representable neither in base 10 nor base 2 floating point, even the decimal value 0.1 cannot be precisely represented by base 2 (IEEE) floating point representation. For example, let's add `0.1` to itself 100 times... `[...Array(100)].reduce((a) => a + 0.1, 0)`. What's the result? Not 10. [Get used to it](https://floating-point-gui.de/) – spender Jul 22 '21 at 09:44
  • Here's a [followup question](https://stackoverflow.com/questions/68482867/what-tricks-does-js-employ-to-show-floating-point-numbers) related to this issue that I just asked. – spender Jul 22 '21 at 10:10

2 Answers2

1

If you are rounding to display the numbers nicely, then instead of rounding, try using toFixed when you are actually rendering the numbers eg

let one = ( ( 100/3 + Number.EPSILON ) * 100 ) / 100;
let two = ( ( 100/3 + Number.EPSILON ) * 100 ) / 100 *3;
//when you print use toFixed
console.log(one, one.toFixed(2));
console.log(two, two.toFixed(2));

This way, you have your true value and a rounded value

pilchard
  • 12,414
  • 5
  • 11
  • 23
PhantomSpooks
  • 2,877
  • 2
  • 8
  • 13
0

I can see only two solutions for this maths question:

  1. Avoid rounding in the first place
  2. Round the result
IAfanasov
  • 4,775
  • 3
  • 27
  • 42