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

Viewed 12299

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?

8 Answers

I got this to simply overwrite it ->

Number.prototype.toFixed = function(fractionDigits, returnAsString = true) {
    var digits = parseInt(fractionDigits) || 0;
    var num = Number(this);
    if( isNaN(num) ) {
        return 'NaN';
    }
    
    var sign = num < 0 ? -1 : 1;
    if (sign < 0) { num = -num; }
    digits = Math.pow(10, digits);
    num *= digits;
    //num = Math.round(num.toFixed(12));
    num = Math.round( Math.round(num * Math.pow(10,12)) / Math.pow(10,12) );
    var ret = sign * num / digits;
    return (returnAsString ? ret.toString() : ret ); // tofixed returns as string always
}
Related