Printing leading 0's in C?

zxcv picture zxcv · Sep 30, 2008 · Viewed 379k times · Source

I'm trying to find a good way to print leading 0's, such as 01001 for a zipcode. While the number would be stored as 1001, what is a good way to do it?

I thought of using either case statements/if then to figure out how many digits the number is and then convert it to an char array with extra 0's for printing but I can't help but think there may be a way to do this with the printf format syntax that is eluding me.

Answer

EvilTeach picture EvilTeach · Sep 30, 2008
printf("%05d", zipCode);

The 0 indicates what you are padding with and the 5 shows the length of the integer number. For example if you use "%02d" (Useful for dates) this would only pad zeros for numbers in the ones column ie.(06 instead of 6). Example 2, "%03d" would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. ie. (number 7 padded to 007 and number 17 padded to 017).