Format floats by padding zeros to the left and right if necessary - Node.js Number

Node.js examples for Number:Float

Description

Format floats by padding zeros to the left and right if necessary

Demo Code

 
/**//  www  .  j a v  a  2 s  . co m
 * Install a function to format floats by padding zeros to the left
 * and right if necessary. Takes two arguments:
 *
 * - numZeros is the number of digits for the integer part.
 *
 * - numDecimals is the number of digits after the point.
 */
Number.prototype.format = function(numZeros, numDecimals) {
  var n = Math.abs(this).toFixed(numDecimals);
  var zeros = Math.max(0, numZeros - n.length + numDecimals + (numDecimals ? 1 : 0));
  var zeroString = Math.pow(10, zeros).toString().substr(1);
  if( this < 0 ) {
    zeroString = '-' + zeroString;
  }
  return (zeroString + n);
};

Related Tutorials