Padding Zero Using Format Specifier :
We can use printf statement for formatting Number as per our requirements. Some times we need to pad zeroes before the actual number in order to fill complete width. Format Specifier used in C Programming is efficient way to pad zero. Let’s look , how to pad zero using format specifier -
- To zero-pad a number, insert a number, preceded by a zero, after the % in the format specifier.
- If you fail to include the zero prefix on the number, it will be padded with spaces and not zeros.
Five-character integer, Padded with Zeros
printf("%05d",i);
Floating point, Padded with zero to left
printf("%07f",f);
Live Example : Padding Zero
#include<stdio.h> int main() { int i = 123; printf("%d\n",i); printf("%05d\n", i ); printf("%07d\n", i ); return( 0 ); }
Output :
123 00123 0000123
Live Example 2 :
#include <stdio.h> int main(void) { float value = 1.0F; printf("value = %07.3f\n", value); return 0; }
Output :
value = 001.000