4

I use a function which rounds to the desired number of decimal places:

function modRound(value, precision)
{
    var precision_number = Math.pow(10, precision);
    return Math.round(value * precision_number) / precision_number;
}

It works correct, but not with 0.565. modRound(0.575, 2) gives 0.58 (correct), but modRound(0.565, 2) gives 0.56; I expect 0.57:

function modRound(value, precision) {
  var precision_number = Math.pow(10, precision);
  return Math.round(value * precision_number) / precision_number;
}
function test(num) {
  console.log(num, "=>", modRound(num, 2));
}
test(0.575);
test(0.565);

Why is this happening and what to do?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Alexey A.
  • 41
  • 1
  • 5

1 Answers1

-1

You can add a very small number like this:

function modRound(value, precision)
{
    var precision_number = Math.pow(10, precision);
    return Math.round((value+0.00000000001) * precision_number) / precision_number;
}
alert(modRound(0.565, 2))

here is the JSFiddle

O_Z
  • 1,515
  • 9
  • 11