gcvt() | Convert float value to string in C

Here, we shall see how a float number (floating point value) can be converted to the string in C language. It is a library function defined in stdio.h header file. This function is used to convert a floating point number to string.
Syntax :

gcvt (float value, int ndigits, char * buf);

float value : It is the float or double value.
int ndigits : It is number of digits.
char * buf : It is character pointer, in this 
variable string converted value will be copied.

Examples :

Input : 123.4567
Output :123.457

Input : 12345.6789
Output : 12345.7
filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to convert float
// value in string using gcvt()
#include <stdio.h>
#define MAX 100
  
int main()
{
    float x = 123.4567;
    char buf[MAX];
  
    gcvt(x, 6, buf);
  
    printf("buffer is: %s\n", buf);
  
    return 0;
}

chevron_right


Output:



buffer is: 123.457

Application: Following Program showing difference in output when division result are stored in
float type(result has precision upto six decimal places) in comparison to when stored directly in string type.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to illustrate
// application of gcvt()
#include <stdio.h>
// called function
void divide(float x, float y)
{
    char buffer[20];
    float z;
    z = x / y;
    // printing normal division result
  
    printf("%f", z);
    gcvt(x / y, 10, buffer);
  
    // printing division result as stored directly in string
    printf("\n%s\n", buffer);
}
int main()
{
    // taking input
    float x = 2.0f, y = 3.0f;
  
    // calling function for division
    divide(x, y);
  
    return 0;
}

chevron_right


Output:

0.666667
0.6666666865


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.