Round to at most 2 decimal places (only if necessary)

Solution:

Use Math.round()

Math.round(num * 100) / 100

Or, to be more precise and to ensure things like the 1.005 round are correctly calculated, use Number.EPSILON:

Math.round((num + Number.EPSILON) * 100) / 100

If the value contains text:

parseFloat("123.456").toFixed(2);

If the value represents a number

var numb = 123.23454;
numb = numb.toFixed(2);

There is one drawback to this: values like 1.5 will result in “1.50”, as output. @minitech offers a solution

var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.

 Math.round  seems like a better solution.But it’s not!In certain instances, it might. NOT Correctly round:

Math.round(1.005 * 1000)/1000 // Returns 1 instead of expected 1.01!

Also, you can use toFixed() NOT  Rounding can be done correctly in certain cases (tested using Chrome v.55.0.2883.87)

Example:

parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.

1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.

I believe this is because 1.555 can actually be described as float 1.55499994.

Solution 1 To use the correct rounding algorithm in a script, you can:

function roundNumber(num, scale) {
  if(!("" + num).includes("e")) {
    return +(Math.round(num + "e+" + scale)  + "e-" + scale);
  } else {
    var arr = ("" + num).split("e");
    var sig = ""
    if(+arr[1] + scale > 0) {
      sig = "+";
    }
    return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
  }
}

https://plnkr.co/edit/uau8BlS1cqbvWPCHJeOy?p=preview

NOTE: This isn’t a solution that works for everyone. There are many rounding algorithms. You can implement them differently depending on your requirements. https://en.wikipedia.org/wiki/Rounding

Solution 2 It’s important to not use front-end calculation and to instead get rounded values from back-end server.

Edit: Another possible solution, although it is not bulletproof.

Math.round((num + Number.EPSILON) * 100) / 100

Sometimes it is possible for a number to be rounded, such as 1.354999999999999999988, and it will give an incorrect result. It should have been 1.35, but it returned 1.36.

Use

function roundToTwo(num) {    
    return +(Math.round(num + "e+2")  + "e-2");
}

I found this on MDN. Their method avoids the problem mentioned with 1.005

roundToTwo(1.005)
1.01
roundToTwo(10)
10
roundToTwo(1.7777777)
1.78
roundToTwo(9.1)
9.1
roundToTwo(1234.5678)
1234.57

 

Exit mobile version