How do you zero-pad a number?
To zero-pad a number, insert a number, preceded by a zero, after the % in the format specifier. This matter is best explained by direct example:
/* Print a five-character integer, padded with zeros. */
printf( “%05d” , i );
/* Print a floating point, padded left of the zero out to
seven characters. */
printf( “%07f” , f );
If you fail to include the zero prefix on the number, it will be padded with spaces and not zeros.
Here is a sample program demonstrating this technique:
#include <stdio.h>
int main()
{
int i = 123;
printf( “%d\n” , i );
printf( “%05d\n” , i );
printf( “%07d\n” , i );
return( 0 );
}
And here is its output:
123
00123
0000123
Cross Reference:
None.
No comments:
Post a Comment