Dave's Brain

Browse - programming tips - javascript zero pad

Date: 2007oct11

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;
}

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.