Zero-pad digits in string

Giles picture Giles · Nov 27, 2008 · Viewed 108.9k times · Source

I need to cast single figures (1 to 9) to (01 to 09). I can think of a way but its big and ugly and cumbersome. I'm sure there must be some concise way. Any Suggestions

Answer

Konrad Rudolph picture Konrad Rudolph · Nov 27, 2008

First of all, your description is misleading. Double is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:

$s = sprintf('%02d', $digit);

For more information, refer to the documentation of sprintf.