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
The correct solution is to store the zip code in the database as a STRING. Despite the fact that it may look like a number, it isn't. It's a code, where each part has meaning.
A number is a thing you do arithmetic on. A zip code is not that.
If you are on a *NIX Machine:
man 3 printf
This will show a manual page, similar to:
0 The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, the converted value is padded on the left with zeros rather than blanks. If the 0 and - flags both appear, the 0 flag is ignored. If a precision is given with a numeric conversion (d, i, o, u, x, and X), the 0 flag is ignored. For other conversions, the behavior is undefined.
Even though the question is for C, this page may be of aid.
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:
snprintf( zipcode, 6, "%05.5d", atoi(zipcode));