Skip to content

A prototype for Number.toFixed in JavaScript

Note

if toFixed is not defined

  1. if (!num.toFixed)
  2. {
  3.  Number.prototype.toFixed = function(precision) {
  4.      var power = Math.pow(10, precision || 0);
  5.      return String(Math.round(this * power)/power);
  6.  }
  7. }
  8. // OR
  9.   Number.prototype.toFixed = function(precision)
  10.   {
  11.      var num = (Math.round(this*Math.pow(10,precision))).toString();
  12.      return num.substring(0,num.length-precision) + “.” +
  13.             num.substring(num.length-precision, num.length);
  14.   }