带有负数的PHP printf()数字填充

When I enter a printf() with a negative parameter for a integer placeholder with a zero padding. The zero padding isn't applied.

php > printf('%02d', -6);
-6

Am I doing something wrong? Or is it a bug?

Per docs:

paddings is applied on the whole string:

An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.

(emphasis mine).

You may want to use the sign specifier if that is acceptable, e.g.:

php > printf('%+03d', -6);
-06
php > printf('%+03d', 6);
+06

Technically it's correct because you're specifying 2 digits and the minus sign accounts for one of those. If you use

printf('%03d', -6); 

you'll get -06.

The "-" counts as a character, so you need to use %03d .

I don't believe this is a bug as 0 padding is often used when working with fields that have a set length, as in characters, so if %02d produced a number with 3 characters the sky might fall.