C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C programming language

Convert float value to string using gcvt() in C language

Learn: How to convert a float value into string using gcvt() function in C programming language?

Here, we will learn how to convert a float number (floating point value) to the string in C language?

What is gcvt()?

It's a library function of stdio.h header, this function is used to convert a floating point number to string.

Syntax:

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

Here,
double value : is the float/double value
int ndigits : number of digits including point (decimal point), for example if you want to get value in xx.yyy format then it should be 6
char * buf : character pointer, in this variable string converted value will be copied.

Program to convert float value in string using gcvt() in C

#include <stdio.h>
#define MAX 50

int main()
{
	float x=0.0f;
	char buf[MAX];
	
	printf("Enter first number: ");
	scanf("%f",&x);
	
	gcvt(x,6,buf);
	
	printf("buffer is: %s\n",buf);
	
	return 0;	
}

Output

Enter first number: 123.45678
buffer is: 123.457






COMMENTS