How do you zero-pad a number in C Programming ?

January 8, 2025 No Comments » Hits : 54






Que : How do you zero-pad a number in C Programming ?

  • 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);

Program :

#include<stdio.h>
int main()
{
int i = 123;
printf("%dn",i);
printf("%05d\n", i );
printf("%07d\n", i );
return( 0 );
}

Output :

123
00123
0000123