tags:

views:

92

answers:

3

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
Silly question - why `%02d` rather than `%2d`? Is the leading zero needed? If so, why is `%4d` OK?
Steve314
@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
@caf - OK, I guess we can tolerate that particular millenium bug
Steve314
+2  A: 
printf("%02d", 9);
Daniel Stutzbach
+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
The first `2` in `%2.2d` is superfluous - `%.2d` is sufficient.
caf