Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding issue in Math.round() & .toFixed()

I used below two methods :

Number.prototype.myRound = function (decimalPlaces) {
    var multiplier = Math.pow(10, decimalPlaces);

    return (Math.round(this * multiplier) / multiplier);
};
alert((239.525).myRound(2));

Mathematically alert should be 239.53 but its giving 239.52 as output. So i tried using .toFixed() function & i got proper answer.

But when i try to get answer for 239.575 it gives again wrong output.

alert((239.575).toFixed(2));

Here output should be 239.58 instead its giving 239.57.

This error creating a bit difference in final output. So can anyone help me to sort this out?

like image 844
Surendra Avatar asked Dec 20 '13 10:12

Surendra


4 Answers

This method will give very correct round result.

function RoundNum(num, length) { 
    var number = Math.round(num * Math.pow(10, length)) / Math.pow(10, length);
    return number;
}

Just call this method.

alert(RoundNum(192.168,2));
like image 125
Kumod Singh Avatar answered Oct 20 '22 12:10

Kumod Singh


Internally, 239.575 cannot be represented exactly. In binary, 0.575 would be something like 1/2 + 1/16 + 1/128 + 1/256 + ....

It just so happens that, represented in binary, the result is slightly less than 239.575. Therefore, Math.round rounds down.

To demonstrate, try this:

alert(239.575 - 239.5)

You would expect the result to be 0.075, but instead you get 0.07499999999998863.

like image 31
Niet the Dark Absol Avatar answered Oct 20 '22 14:10

Niet the Dark Absol


Just use Math.round

function round(figureToRound){
    var roundOff = Math.round((figureToRound* 100 ).toFixed(2))/100;
    return roundOff;
}

console.log(round(1.005));

This will help the rounding off issue completely.

like image 3
Srinath Mahe Avatar answered Oct 20 '22 12:10

Srinath Mahe


round() will do the trick.Try This:

var v= Math.round(239.575 * 100) / 100;
alert(v);

Working FIddle

like image 2
Milind Anantwar Avatar answered Oct 20 '22 13:10

Milind Anantwar