Encoders
Hub for Computer Whizzes Register to join us

Encoders > More... > C > Program

/* Function itoa(n,s,w) to convert a number to string and the converted
   number must be padded with blanks on the left if necessary to make it
   atleast w characters wide. */

#include <stdio.h>

void itoa(int number, char string[], int w);

main()
{
	char a[100];
	itoa(12345.67,a,8);
        printf("%s\n",a);
}

void itoa(int n, char s[], int w)
{
        void shift(char s[],int i);
	int i=0, sign;
        if((sign=n)<0)
		n = -n;
	s[0]='\0';
	do
		shift(s,i), s[0]=n%10+'0', n/=10, i++, w--;
        while(n>0);

        if(sign<0)
		shift(s,i), s[0]='-', i++, w--;
        for(; w>0; i++,w--)
		shift(s,i), s[0]='0';

}

void shift(char s[],int i)
{
	int j;
        for(j=i; j>=0 ; j--)
		s[j+1]=s[j];
}