I was recently working on a project wherein I needed to present a number padded on the left with zeroes. Most languages have some sort of formatter method which would allow you to do that, but not JavaScript. Instead of following the path of other languages, JavaScript opts to give the developer opportunities to be creative.

After a quick search, I ran across a very elegant solution from Pau Sanchez which I have turned into a the following function and added some smarts to allow the padding to be changed as necessary.

var lpad = function(value, padding) {
    var zeroes = "0";
    
    for (var i = 0; i < padding; i++) { zeroes += "0"; }
    
    return (zeroes + value).slice(padding * -1);
}

Note that this doesn’t account for numbers which are longer than the padding value; they get cut off. Most of the time you deal with left padded numbers, you’re dealing with a fixed width and this isn’t going to be a problem. I’ll leave it as an exercise for the user, if this is not the current case for you.

Here it is again in CoffeeScript:

lpad = (value, padding) ->
  zeroes = "0"
  zeroes += "0" for i in [1..padding]

  (zeroes + value).slice(padding * -1)

blog comments powered by Disqus

About me


I live in the greater Kansas City area with my beautiful wife, our two great kids, and our dog. I've been programming using Open Source technologies since '97 and I'm currently an independent software developer specializing in Ruby on Rails and iOS. I am for hire.

Freelancing Digest


The Freelancing Digest is a curated newsletter aimed specifically at freelancers. Delivered on the 1st and 15th of the month, each issues contains links to some of the best articles on the web to help you establish and grow your freelancing business.