How to simply convert a float to a string in c?

The second parameter is the format string after which the format arguments follow:

fprintf(fPointer, "%f", amount);

%f tells fprintf to write this argument (amount) as string representation of the float value.

A list of possible format specifiers can (for example) be found here.


If you can use C99 standard, then the best way is to use snprintf function. On first call you can pass it a zero-length (null) buffer and it will then return the length required to convert the floating-point value into a string. Then allocate the required memory according to what it returned and then convert safely.

This addresses the problem with sprintf that were discussed here.

Example:

int len = snprintf(NULL, 0, "%f", amount);
char *result = malloc(len + 1);
snprintf(result, len + 1, "%f", amount);
// do stuff with result
free(result);

By using sprintf() we can convert from float to string in c language for better understanding see the below code

#include <stdio.h>
int main()
{
   float f = 1.123456789;
   char c[50]; //size of the number
    sprintf(c, "%g", f);
    printf(c);
    printf("\n");
}

Hope this will help you.

Tags:

C