.toFixed() function when calculating input


Hi, so I know how to use this function when you have a straightforward figure, but how can you make it work when you have to calculate before you round it up?

The below isn’t working for me:


OK to answer my own question, use brackets:
(I’m sure I tried this before but it didn’t work?!)


It seems like toFixed() is a better solution, but it is not! In some cases it will NOT round correctly. Also, Math.round() will NOT round correctly in some cases.

To correct the rounding problem with the previous Math.round() and toFixed(), you can define a custom JavaScript rounding function that performs a “nearly equal” test to determine whether a fractional value is sufficiently close to a midpoint value to be subject to midpoint rounding. The following function return the value of the given number rounded to the nearest integer accurately.

Number.prototype.roundTo = function(decimal) {
  return +(Math.round(this + "e+" + decimal)  + "e-" + decimal);

var num = 9.7654;
console.log( num.roundTo(2)); //output 9.77