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.
Zipcode is a highly localised field, many countries have characters in their postcodes, e.g., UK, Canada. Therefore in this example you should use a string / varchar field to store it if at any point you would be shipping or getting users/customers/clients/etc from other countries.
However in the general case you should use the recommended answer (
printf("%05d", number);
).If you need to store the zipcode in a character array zipcode[] , you can use this:
You place a zero before the minimum field width:
More flexible.. Here's an example printing rows of right-justified numbers with fixed widths, and space-padding.
The function and macro are designed so the printfs are more readable.