Function to add zeros to the left of a number - Node.js Number

Node.js examples for Number:Format

Description

Function to add zeros to the left of a number

Demo Code


'use strict';// ww  w.  ja  v  a 2 s.c o  m

/**
 * Function to add zeros to the left of a number.
 *
 * @param {Number} size maximum number of zeros to display on the left
 * @return {string}
 */
Number.prototype.pad = function(size) {
  var s = String(this);
  while (s.length < (size || 2)) {s = "0" + s;}
  return s;
};

Related Tutorials