How do get numbers to display as two digits in C?
Asked Answered
I

3

66

For C programming. How do i get numbers to be displayed as 00, 01, 02, 03, instead of 0, 1, 2, 3. I just need 0 before the number until 10.

i know when your doing decimals you can do "%.2f" etc. but what about in reverse for integers?

here is what I am using...**

printf("Please enter the hours: ");
    scanf ("%d",&hour);
printf("Please enter the minutes: ");
    scanf ("%d",&minute);
printf("Please enter the seconds: ");
    scanf ("%d",&second);
printf("%d : %d : %d\n", hour, minute, second);

}

I need the numbers to display as 00 : 00 : 00

??

Indiana answered 31/1, 2013 at 3:14 Comment(1)
Has to be a dupe, right?Rydder
C
95

You need to use %02d if you want leading zeroes padded to two spaces:

printf ("%02d : %02d : %02d\n", hour, minute, second);

See for example the following complete program:

#include <stdio.h>
int main (void) {
    int hh = 3, mm = 1, ss = 4, dd = 159;
    printf ("Time is %02d:%02d:%02d.%06d\n", hh, mm, ss, dd);
    return 0;
}

which outputs:

Time is 03:01:04.000159

Keep in mind that the %02d means two characters minimum width so it would output 123 as 123. That shouldn't be a problem if your values are valid hours, minutes and seconds, but it's worth keeping in mind because many inexperienced coders seem to make the mistake that 2 is somehow the minimum and maximum length.

Copyholder answered 31/1, 2013 at 3:16 Comment(3)
what is the solution for tuning the maximum length?Tsunami
@rahman, there's no good solution for specifying maximum length. If you have the value 123 and you shoehorn it into two digits, you'll get one of 12 or 23, depending on how you decide to do it. Neither of those is acceptable in my opinion. Far better to output ** as an indication that something's gone horribly wrong.Copyholder
This also works for hexa printf("%02X", ... );Sophy
P
45

Use the format: %02d instead. The 0 means to pad the field using zeros and the 2 means that the field is two characters wide, so for any numbers that take less than 2 characters to display, it will be padded with a 0.

Paring answered 31/1, 2013 at 3:16 Comment(0)
O
7

"%.2d" is what should be used. The rule is basically;

"%<minimum-characters-overall>.<minimum-digits>d".

For example:

"%6.3d" will print 6 characters overall and a minimum of 3 digits.

Orb answered 18/7, 2020 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.