Javascript Number roundToPrecision

by on Nov.17, 2011, under Javascript, Numbers

Needed a cross-browser function round to a given precision. Cannot rely on toFixed()

Number.prototype.roundToPrecision = function( precision ) {
  if (precision===undefined) { precision = 2; }
  var multiplier = Math.pow(10,precision);
  return Math.round(this*multiplier)/multiplier; 

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!


A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org