开发者

Number representation problem in php

It is a simple thing but i don't get answer for that.

I am generated auto generation id conca开发者_如何学Ctenate with year 100001, 100002 like that, in this 10 is year 0001 is auto generation numbers. When i split the year and number then getting add one value is 2 for 0001. but i need as 0002.

Adding value is 0001+1, 0002+1, 0010+1, 0099+1

Now the answer are 2, 3, 11, 100 like that

But i need like that 0002,0003,0011,0100

Thanks in advance.


$var = sprintf ('%04d', $var);

See sprintf manual.


0001 is not a number, it's a string. When you add 1 to it, PHP converts it to a number (1), then adds 1 to it, so you end up with 2. What you want to do is pad the number with 0's, converting it back to a string. You can use sprintf, as others have suggested, or str_pad.

str_pad(1, 4, '0', STR_PAD_LEFT);


You can use good old sprintf to format numbers.

$a = 1;
$f = sprintf("%06s", $a);
echo $f;

Should print "000001".

Documentation: http://php.net/manual/en/function.sprintf.php

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜