Scriptplayground

 Print Page | Close Window

Pad Number With Zeros

Pad a number with zeros. Shows you how to achieve that using a function for reusability.

A simple way to use a function that pads a number with x amount of zeros.

function padWithZeros($s, $n) {
  return sprintf("%0" . $n . "d", $s);
}

We use sprintf() that accepts 2 arguments. The first one is the conversion string and the second is the string to convert. The conversion string starts with a "%" followed by a conversion in order. In this case we want to pad zeros to a point determined in calling the function.

To use this function you make a call like this

print padWithZeros("1", 5);

That pads the number 1 with four zeros to equal five places.

You can use sprintf for a series of tasks, including but not limited to padding, justification, custom padding etc...

Finally here is the function with a call in one place for easy copy & pasting.

function padWithZeros($s, $n) {
  return sprintf("%0" . $n . "d", $s);
}

print padWithZeros("1", 5);

Find this article at:
http://scriptplayground.com/tutorials/php/Pad-Number-With-Zeros/