SMH
SMH

Reputation: 1099

How to round the sum of decimal numbers more accurately in javascript

I am trying to find a way to round the sum of an array of numbers in more accurate way. for example giving an array of [33.33, 33.33, 33.33] the sum is 99.99 in this case I don't want to round the sum to be 100. but if the array of numbers was [33.3333 , 33.3333, 33.3333] then it should round the sum to 100. Using Math.round() is rounding always to 100 even if you have an array of [33.22 , 33.33 , 33.33]

Upvotes: 0

Views: 972

Answers (2)

Shubham Shukla
Shubham Shukla

Reputation: 226

The better solution to round off a number is demoed here

function precisionRound(number, precision) {
  var factor = Math.pow(10, precision);
  return Math.round(number * factor) / factor;
}

console.log(precisionRound(99.99, 2)); //99.99
console.log(precisionRound(99.9999, 2)); //100

Upvotes: 3

Martin Adámek
Martin Adámek

Reputation: 18389

You could multiply before rounding to have different precision:

var a = 99.99;
var b = 99.9999;
var precision = 100;

console.log(a, Math.round(a), Math.round(a * precision) / precision);
console.log(b, Math.round(b), Math.round(b * precision) / precision);

Upvotes: 3

Related Questions