This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

code for converting float to string

Is there any library function in KEIL C which converts a floating point into string. If not can somebody give the appropriate code.

Parents
  • // This code converts the given float values to a string
    // input argumentsto the function are 1. Float value that to be converted 2. Number of digits at the output string 3. The string variable to store the converted results


    /* Perfect float to string Conversion c program */


    #include <stdio.h>

    void ftostr(double num, int digits,char *buff)
    {
    int i_temp = (int)num;

    float f_temp = num-i_temp;

    char temp_s[20];
    int i_len = i_temp>0 ?1:2;

    int ref_len = i_len;
    int var = i_temp;

    while(var)
    {
    i_len += 1;
    var /=10;
    }

    int temp_len = i_len;

    for(int i=0;i<digits;i++)
    {
    if(temp_len==ref_len)
    {
    temp_s[i_len-2-i]='0' + i_temp%10;
    temp_len -= 1;
    }
    else if(temp_len>ref_len)
    {
    temp_s[i_len-2-i]='0' + i_temp%10;
    i_temp /= 10;
    temp_len -= 1;
    }
    if(i_len-1 == i)
    {
    temp_s[i] = '.';
    temp_len -= ref_len==2?1:0;
    }
    else if(temp_len == 0)
    {
    temp_s[i] =(int)(f_temp*10)+'0';
    f_temp = f_temp *10;
    f_temp = f_temp - (int)f_temp;
    }
    }

    for(int i=0;i<=digits;i++)
    {
    buff[i] = temp_s[i];
    }
    }


    int main()
    {
    float a = 10.2563;
    char tx[100];

    ftostr(a,10,tx);

    printf("\n %s",tx);

    return 0;
    }

Reply
  • // This code converts the given float values to a string
    // input argumentsto the function are 1. Float value that to be converted 2. Number of digits at the output string 3. The string variable to store the converted results


    /* Perfect float to string Conversion c program */


    #include <stdio.h>

    void ftostr(double num, int digits,char *buff)
    {
    int i_temp = (int)num;

    float f_temp = num-i_temp;

    char temp_s[20];
    int i_len = i_temp>0 ?1:2;

    int ref_len = i_len;
    int var = i_temp;

    while(var)
    {
    i_len += 1;
    var /=10;
    }

    int temp_len = i_len;

    for(int i=0;i<digits;i++)
    {
    if(temp_len==ref_len)
    {
    temp_s[i_len-2-i]='0' + i_temp%10;
    temp_len -= 1;
    }
    else if(temp_len>ref_len)
    {
    temp_s[i_len-2-i]='0' + i_temp%10;
    i_temp /= 10;
    temp_len -= 1;
    }
    if(i_len-1 == i)
    {
    temp_s[i] = '.';
    temp_len -= ref_len==2?1:0;
    }
    else if(temp_len == 0)
    {
    temp_s[i] =(int)(f_temp*10)+'0';
    f_temp = f_temp *10;
    f_temp = f_temp - (int)f_temp;
    }
    }

    for(int i=0;i<=digits;i++)
    {
    buff[i] = temp_s[i];
    }
    }


    int main()
    {
    float a = 10.2563;
    char tx[100];

    ftostr(a,10,tx);

    printf("\n %s",tx);

    return 0;
    }

Children
No data