RedVodkaJelly Logo

Pad a JavaScript Number

POSTED AT 17:51 on 4th November 2007

Sometimes when working with numbers in JavaScript you will want to pad a number out to ensure it has any leading zeros required (for currency and dates etc). Here’s a simple bit of code that does just that:

  1. function pad(number, length){
  2.    var str = "" + number;
  3.    while(str.length<length){
  4.       str = ’0′+str;
  5.    }
  6.    return str;
  7. }

Simply call the function with your number and the length it needs padding to.

Comments

  • Matt

    The code on this page is completely mangled and non functional.

    Posted at 03:08 on 18th June 2008
  • Jacob Wyke

    Hi Matt,

    Thanks for letting me know. I recently upgraded my server and a lot of my data got damaged in the process.

    Posted at 13:16 on 29th July 2008
  • David

    I tested it. It is working.

    Posted at 19:16 on 12th November 2009

Leave a Comment