SitePoint Sponsor |
|
User Tag List
Results 1 to 7 of 7
-
Jun 10, 2003, 05:44 #1
Number formatting and leading zeros
After seeing this post I got thinking about how a month is displayed as "1" and not "01" and would like to know if there is a better way to set up how a number should be displayed. (I'm not talking about using the date format here, I'm talking about leading zeros for any number)
Is there not some way of initialising the variable format as well as the value when you declare it? Floats, ints, doubles etc are all well and good but when it comes to leading zeros, most solutions I have seen involve converting the number into a string which may not always be ideal.
-
Jun 10, 2003, 06:27 #2
- Join Date
- Oct 2002
- Location
- Scotland
- Posts
- 3,631
- Mentioned
- 2 Post(s)
- Tagged
- 0 Thread(s)
AFAIK there is no other way to add leading zeros other than to prepend them as a string.
-
Jun 10, 2003, 06:32 #3
Originally Posted by siteguru
Are all programming languages like this?
-
Jun 10, 2003, 06:38 #4
- Join Date
- Mar 2002
- Location
- Osnabrück
- Posts
- 1,003
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Hi.
There are some ways, using printf or the other month letter which includes the leading zero
PHP Code:// using date
echo date ('d - m - Y', time());
// appending zeroes to a string
printf('%02d', 1);
// should print 01
-
Jun 10, 2003, 06:45 #5
- Join Date
- Oct 2002
- Location
- Scotland
- Posts
- 3,631
- Mentioned
- 2 Post(s)
- Tagged
- 0 Thread(s)
Originally Posted by Chris82
-
Jun 10, 2003, 07:52 #6
- Join Date
- Nov 2001
- Location
- Singapore
- Posts
- 617
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
i got this from php.net
PHP Code:$i = 1;
str_pad($i,2, "0",STR_PAD_LEFT)
-
Jun 11, 2003, 04:08 #7
Hi guys, thanks for the thoughts.
I've seen the stuff on php.net (including the number_format function, which is as siteguru said primarily for formatting the decimal and thousands separator) As I mentioned, there only seems to be the option to convert the number to a string to add leading zeros. Common examples, I perhaps should have posted in the first case:
PHP Code:$length = "5";
$number = "223";
// Method 1
echo str_repeat("0", ($length-strlen ($number))) . $number;
// Method 2
echo str_pad($number, $length, "0", STR_PAD_LEFT);
I can't recall my university days much (alcoholic haze) but maybe there was some way to do this in C++?
I know all is not lost, there are always work-arounds and things like string arithmatic can be achieved, but I thought this thread would create some strong arguments for something that perhaps is missing from our beloved language.
Bookmarks