Hithesh kumar
Hithesh kumar

Reputation: 1036

How to round of decimal numbers and get exact sum if added?

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 ?

Upvotes: 0

Views: 570

Answers (2)

PhantomSpooks
PhantomSpooks

Reputation: 3540

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

Upvotes: 1

IAfanasov
IAfanasov

Reputation: 4993

I can see only two solutions for this maths question:

  1. Avoid rounding in the first place
  2. Round the result

Upvotes: 0

Related Questions