any existing function to do that in c?
+11
A:
sprintf with formatting codes like %02d will give you two decimal places.
here's an example of the command sprintf( string, "file.%d", file_number );
Here it puts the string "file.2" into the variable named string, assuming that 2 was in the variable named file_number.
you can use multiple like so: sprintf(str, "%02d/%02d/%4d",day,month,year);
Look up the specs on sprintf for other kinds of formatting like floating point significant digits.
Karl
2010-07-22 00:51:45
Silly question - why `%02d` rather than `%2d`? Is the leading zero needed? If so, why is `%4d` OK?
Steve314
2010-07-22 01:03:02
@Steve314: `%2d` will pad with spaces, `%02d` with 0s. `%4d` is presumably OK because the code is only specified to work with years after 999 ;)
caf
2010-07-22 01:05:57
@caf - OK, I guess we can tolerate that particular millenium bug
Steve314
2010-07-22 01:11:24
+3
A:
Along with "%02d"
you can use "%2.2d"
if you prefer. The latter style is handy when/if the actual width is in a variable so you do something like this:
int width = 2;
int value = 9;
printf("%*.*d", width, width, value);
Jerry Coffin
2010-07-22 01:00:24