02 Votes

PHP: Echo Number with leading Zeros

Question by Guest | 2014-09-12 at 19:10

Is there any possibility to give numbers some leading zeros in PHP? Namely, that the number of places is always of equal length?

That means when considering the numbers 2 and 10, I would like to have made "002" and "010" out of them. The reason: I would like to output the numbers in a table and it is looking better when all values are written exactly under each other.

How is it possible to format numbers or digits in such a way using PHP? I think, the most difficult thing at this task is, that sometimes, you need only one zero and sometimes you need two zeros or even no zero at all to fill the string.

ReplyPositiveNegative
0Best Answer4 Votes

Just use the function sprintf(). You can pass a format-string and the number you would like to output to this function.

Here is a small example:

$x = 2;
$y = 10;

sprintf("%03d", $x);          // 002
sprintf("%03d", $y);          // 010
sprintf("%02d", $x);          // 02
sprintf("%02d %02d", $x, $y); // 02 10

The "d" in the format-string is standing for an integer number, the "03" is caring about filling 3 places.

The two last lines are showing examples of how to use this function to fill 2 places and to output more than one numbers at once.

Another function that could be interesting for you is str_pad() - this function is working with strings instead of numbers.
2014-09-14 at 18:46

ReplyPositive Negative
Reply

Related Topics

PHP: Current Date and Time

Tutorial | 0 Comments

PHP: Rounding Numbers

Tutorial | 0 Comments

PHP: Determine Week Number

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.