Maddy
Maddy

Reputation: 590

Add trailing zeros to string

How can I add some trailing zeros to a string like in following example:

$number= sprintf("%04s", "02");
echo $number;

This displays 0002 but I want 0200

Upvotes: 0

Views: 1545

Answers (3)

Ashley
Ashley

Reputation: 1489

You could use str_pad:

str_pad('02', 4, '0');

Upvotes: 0

jeroen
jeroen

Reputation: 91792

If you don't know how long your original input will be and you want the padding to be flexible (I assume that is what you need...), you can set the padding to the other side like this:

$number= sprintf("%-04s", "02");
                   ^ here
echo $number;

Upvotes: 5

tino.codes
tino.codes

Reputation: 1507

Have a look at http://php.net/manual/en/function.str-pad.php

$number= str_pad("02", 4, 0);
echo $number;

Upvotes: 2

Related Questions