Format a number in PHP |
Format a number in PHP |
DeaPeaJay |
Oct 21 2006, 12:41 PM
Post
#1
|
Advanced Member Group: Members Posts: 103 Joined: 21-September 06 From: East Tennessee - USA Member No.: 191 |
I have a really simple question that I can't seem to find anywhere online cause I'm not sure what to search for.
I have an integer and I need to format it to always be three long (ie. 001). But I can't figure out how to do this in PHP. I tried rounding it with round() like this "round(1, -3)" but that didn't work. |
Christian J |
Oct 21 2006, 01:36 PM
Post
#2
|
. Group: WDG Moderators Posts: 9,630 Joined: 10-August 06 Member No.: 7 |
How about counting the string lenght of the integer*, then prepend zero characters if needed?
* I assume PHP will automatically convert an integer to string when using e.g. strlen(). |
DeaPeaJay |
Oct 21 2006, 02:10 PM
Post
#3
|
Advanced Member Group: Members Posts: 103 Joined: 21-September 06 From: East Tennessee - USA Member No.: 191 |
I can always resort to that, it just seems like its something there should be a function for, since there is in most everything else.
|
Sparkyg |
Oct 21 2006, 05:21 PM
Post
#4
|
Member Group: Members Posts: 46 Joined: 29-September 06 From: Suffolk UK Member No.: 270 |
hi there
you can use the string pad function AFAIK there is no number format function that can do it. http://us2.php.net/manual/en/function.str-pad.php cheers Sparky |
DeaPeaJay |
Oct 21 2006, 05:37 PM
Post
#5
|
Advanced Member Group: Members Posts: 103 Joined: 21-September 06 From: East Tennessee - USA Member No.: 191 |
Hey thanks Sparky! That's perfect!!
|
Sparkyg |
Oct 21 2006, 05:58 PM
Post
#6
|
Member Group: Members Posts: 46 Joined: 29-September 06 From: Suffolk UK Member No.: 270 |
|
Brian Chandler |
Oct 22 2006, 05:26 AM
Post
#7
|
Jocular coder Group: Members Posts: 2,460 Joined: 31-August 06 Member No.: 43 |
I have a really simple question that I can't seem to find anywhere online cause I'm not sure what to search for. I have an integer and I need to format it to always be three long (ie. 001). But I can't figure out how to do this in PHP. I tried rounding it with round() like this "round(1, -3)" but that didn't work. I cannot imagine why or how round(1, -3) would be expected to do anything like this. The entire C formatting functionality is available - just try sprintf() in the PHP library. IIRC, "%3d" means a 3-digit decimal number, and "%03d" means a zero-padded same. So I think sprintf("%03d", $value) will give you what you want. (If you don't know the C 'print' family formatting stuff, it's well worth learning.) |
Lo-Fi Version | Time is now: 28th March 2024 - 04:14 PM |