Is it possible to convert Float or double in a string???

Any idea??

> Any idea??

#include <stdio.h>

int main( void )
{
    float d_n = 123.45;
    char s_cp[13] = { '\0' };
    char s_cnp[4] = { '\0' };
    
    /*
     * with sprintf you need to make sure there's enough space
     * declared in the array   
     */    
    sprintf( s_cp, "%.2f", d_n ); 
    printf( "%s\n", s_cp );
    
    /*
     * snprinft allows to control how much is read into array.
     * it might have portable issues if you are not using C99
     */
    snprintf( s_cnp, sizeof s_cnp - 1 , "%f", d_n );
    printf( "%s\n", s_cnp );
    
    getchar();
    return 0;    
}

/* output :
 * 123.45 
 * 123
 */

Thanks Aia,

I am not using C99 compiler. I am writing code for micro controller. I have very limited memory to accomplish task. snprintf is not working with my compiler. Is snprintf memory constraint?

Is there any way to get the job done utilizing minimum memory??

I thank you for your help.

rgds

Mr. Gemni7 I do not know the answer to your questions. All that I know is that for compilers previous to the ISO C99 standards, snprintf() is not an obtion. In this case you will have to use the more portable function sprintf. Making sure you allow for enough space in the array to hold the float convertion.

Separate the number into 2 values at the decimal.
Convert the numbers into single integers using / and * and %
Convert each single digit to character (add 48)
Load the character values into your output array

Split the number into two parts..Before decimal and after decimal.
Use _ultoa() to convert both of the above parts into strings.
Combine the two strings in order with strcat().

This should work.It did for me..

This article has been dead for over six months. Start a new discussion instead.