• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Pad a number with leading zeroes in Javascript

Pad a number with leading zeroes in Javascript

As far as I have been able to tell there isn’t a built-in way with Javascript to pad a number with leading zeroes to make it a fixed width like with e.g. sprintf in other programming langages. This post looks at a way to pad a number with zeroes with Javascript.

Please note: this doesn’t work for negative numbers; it was designed specifically for padding with leading a zeros a number which will be used in date formats where negatives are not possible (there will be a post later this week about this). I’ll write another post to revise what’s here and will work with negative numbers.

The following function will pad a number with leading zeroes so the resulting string is "length" length. For example if length is 2 and the passed in number is 5 the value returned is 05.

function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}

Some code to test the above:

document.write(pad(1, 1) + '<br />');
document.write(pad(1, 2) + '<br />');
document.write(pad(15, 2) + '<br />');
document.write(pad(1, 3) + '<br />');
document.write(pad(15, 3) + '<br />');
document.write(pad(155, 3) + '<br />');
document.write(pad(1, 4) + '<br />');
document.write(pad(1, 5) + '<br />');

And the resulting output:

1
01
15
001
015
155
0001
00001

On Tuesday I’ll look at a second solution if you only ever need to pad a number to two numbers, like you would for days and months, and hours, minutes and seconds.

Check Out These Related posts:

  1. Javascript UNIX timestamp converter
  2. Vim Show Line Numbers
  3. Pad a number with leading zeroes in Javascript – Improved
  4. Pad a number to two digits with Javascript

Filed Under: Javascript

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap