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 and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.