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.
Related Topics
PHP: Save MySQL Result in Array
Info | 0 Comments
PHP: Current Date and Time
Tutorial | 0 Comments
PHP: Rounding Numbers
Tutorial | 0 Comments
JavaScript: Remove leading zeros
Tip | 2 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
PHP: Determine Week Number
Tutorial | 0 Comments
Send Form Input as an Array to PHP Script
Tip | 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.
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:
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