Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

FILE * fPointer;
float amount = 3.1415;
fPointer =fopen("vending.txt","w");
fprintf(fPointer ,amount);
printf("The file has been created for the first time and we added the value %f" , amount);
fclose(fPointer);

I am trying to save a float number to a text file but when i try to run this code it triggers a compiling errors because the function fprintf expects the second parameter to be an array of characters so how can i convert my float to a string so i can pass it , i come from a c# background where something like .toString() is possible so is there any thing like that in c to directly cast a float to a string ?

like image 627
Fady Sadek Avatar asked Dec 30 '16 09:12

Fady Sadek


3 Answers

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.

like image 194
René Vogt Avatar answered Oct 11 '22 11:10

René Vogt


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);
like image 7
Nikola Novak Avatar answered Oct 11 '22 09:10

Nikola Novak


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.

like image 4
kumar Avatar answered Oct 11 '22 10:10

kumar