Help - Search - Members - Calendar
Full Version: Format a number in PHP
HTMLHelp Forums > Programming > Server-side Scripting
DeaPeaJay
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
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
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
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
Hey thanks Sparky! That's perfect!!
Sparkyg
QUOTE(DeaPeaJay @ Oct 21 2006, 05:37 PM) *

Hey thanks Sparky! That's perfect!!


no problems.. any time
Brian Chandler
QUOTE(DeaPeaJay @ Oct 22 2006, 02:41 AM) *

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.)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2024 Invision Power Services, Inc.