Padding numbers

We are sometimes faced with the need to pad numbers to a certain range. For example, suppose we want to display a number in five possible digits, such as 00042. One obvious solution would be to use the iterative approach and prepend characters, but there are a few cleaner solutions.

Getting ready

First, we need to take a look at some of the functions that we are going to use. Let's take a look at the Array.join(separator) method that can be applied to create joined text from a list of elements:

new Array('life','is','life').join('*')

This will result in "life*is*life" that shows fairly simple elements that are joined with a given separator. Another method that is of interest is Array.slice(begin[, end]) that returns a copy of a portion ...

Get HTML5 Data and Services Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.