8

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?

6
  • 1
    Interesting but 239.375.toFixed(2) returns "239.38" in Chrome 31 (Mac)... :)
    – VisioN
    Commented Dec 20, 2013 at 10:07
  • 1
    possible duplicate of broken toFixed implementation
    – VisioN
    Commented Dec 20, 2013 at 10:08
  • @VisioN Not here. Which browser are you using? I'm on the latest FF on Ubuntu. Commented Dec 20, 2013 at 10:10
  • @CedricReichenbach Chrome 31 on MacOS
    – VisioN
    Commented Dec 20, 2013 at 10:10
  • Simpler solution: Truncate to decimals function
    – David
    Commented May 25, 2017 at 15:42

10 Answers 10

12

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));
3
7

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.

2
  • Though it is true, I haven't ever seen such 'problems' in other languages... That's definitely what must be improved in JavaScript.
    – VisioN
    Commented Dec 20, 2013 at 10:17
  • @VisioN It's true of any language that uses double-precision floating-point numbers. Which is almost all of them, except those with fixed-point or arbitrary-precision systems. Commented Dec 20, 2013 at 10:19
3

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.

2
  • Works on all cases fro me. round(239.575 - 239.5) 0.08 round(239.575) 239.58 round(239.525) 239.53 round(1.005) 1.01
    – googamanga
    Commented Dec 27, 2017 at 16:58
  • Doesn't work for round(0.07499). It returns 0.08, instead of 0.07
    – dugokontov
    Commented May 28, 2020 at 12:41
2

round() will do the trick.Try This:

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

Working FIddle

1
  • this will not work with negative values for example -239.575 will give you -239.57 but it should be -239.58 Commented Jan 22 at 9:46
2

The problem is probably floating point inaccuracy, thus you might get different results in different cases (different gathering of a number, different browsers etc.).

See also this: toFixed(2) rounds "x.525" inconsistently?

0

In my software I use this:

(require DecimalJS)

Number.prototype.toFixed = function(fixed) {
    return (new Decimal(Number(this))).toFixed(parseFloat(fixed) || 
0);
};


var x = 1.005;
console.log( x.toFixed(2) ); //1.01
0
function bestRound(val, decimals){
    decimals = decimals || 2;
    var multiplier = Math.pow(10, decimals)
    return Math.round((val * multiplier ).toFixed(decimals)) / multiplier;
  }

bestRound(239.575 - 239.5)   0.08
bestRound(239.575)         239.58
bestRound(239.525)         239.53
bestRound(1.005)             1.01
0

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
}
0

A method to deal only with this specific edge cases preserving the

function adjustRounding(number, fractionDigits) {
    let parts = number.toString().split('.');
    let fraction = parts[1];

    if (fraction && fraction.length > fractionDigits && fraction[fraction.length - 1] === '5') {
        number = parseFloat(parts[0] + '.' + fraction + '1');
    }

    return number.toFixed(fractionDigits);
}
0

many answers here are working only with positive numbers but those solutions will fail with negative. for example -1.875 should return -1.88 not -1.87 so you need to check if number is negative and execute different logic

function rounding(number) {
 if(number < 0) { // check if number is negative
   number = Math.abs(number); // remove minus from number to make it positive
   var roundedNumber = (Math.round(number * 100) / 100) * -1 // round it like positive but at the end multiple it -1 to make it negative again;
 } else {
   var roundedNumber = Math.round(number * 100) / 100
 }
 console.log(roundedNumber);
 return roundedNumber;
}

var number = 1.87501;

rounding(number);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.