round a number in javascript

here’s the code for arbitrary precision rounding in javascript.

Number.prototype.round = function(precision) {
  if (typeof(precision) != "number") precision = 2;
  var y = Math.pow(10, precision);
  return Math.round(this * y) / y;
};

use it thusly:

1.49.round(0) == 1
1.5.round(0) == 2

About this entry