开发者

How do I do this in PHP..Number formatting

开发者 https://www.devze.com 2023-03-06 06:01 出处:网络
Hey im sure this is pretty simple..but im not exactly sure how to ask the question so searching the forums were difficult.

Hey im sure this is pretty simple..but im not exactly sure how to ask the question so searching the forums were difficult.

I have a variable with a number in it ... lets s开发者_Go百科ay $number.....the variable has a single regular number...1 or 2 or 34 or 102 etc

I need to change it to something like this

001, 002, 034, 102

So the first 2 place values are 00 for single digit numbers or 0 of double digits.

Any ideas?

Thanks for your help

Craig


You can use sprintf.

$num = 2;
$num = sprintf("%03u", $num);

echo $num; // prints 002


str_pad()

echo str_pad($number,3,'0',STR_PAD_LEFT);


you could do something like this:

$number; //your number
$len=strlen($number);
$res="";
for ($i=0; $i<3-$len;$i++)
    $res.="0";
$res.=$number; 
0

精彩评论

暂无评论...
验证码 换一张
取 消