Programming Tips - javaScript has no sprintf() ... how can I zero pad a number?

Date: 2007oct11 Language: javaScript Q. javaScript has no sprintf() ... how can I zero pad a number? A. Use this function:
// n = number you want padded // digits = length you want the final output function zeroPad(n, digits) { n = n.toString(); while (n.length < digits) { n = '0' + n; } return n; } function exampleUse() { var a; // Pad 123 to 8 digits a = zeroPad(123, 8); alert('a='+ a); }
By the way, naive Java version
static String zeroPad(String n, final int digits) { while (n.length() < digits) { n = '0' + n; } return n; }