Your Browser is not longer supported

Please use Google Chrome, Mozilla Firefox or Microsoft Edge to view the page correctly
Loading...

{{viewport.spaceProperty.prod}}

gcvt - Convert a floating-point number to a string

&pagelevel(4)&pagelevel

Definition

#include <stdlib.h>

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

gcvt converts a floating-point number value to a string of digits and stores the string in the
area pointed to by buf. A pointer to this area is returned as a result.

Depending on the structure of the floating-point value to be converted, the output format
corresponds to

  • the FORTRAN F format: n significant digits, no leading or trailing zeros from value, a
    negative sign if required, and a decimal point (if there are any non-zero digits after the
    decimal point)

  • or the FORTRAN E format (exponential notation).

Parameters 

double value

Floating-point value to be edited for output.

int n

Number of digits in the resulting string (calculated as of the first non-zero digit in the
floating-point value to be converted).

If n is less than the number of digits in value, the least significant digit is rounded.
If n is greater, the string ends with the last non-zero digit.

char *buf

Pointer to the converted string.
The memory area to which buf points should be at least (n + 4) bytes in size!

Return val.

Pointer to the converted string.

gcvt terminates the string with the null byte (\0).

Notes

Invalid parameters, such as an integer instead of a double value, cause the program to
abort!

It is your responsibility to ensure that the result pointer buf points to a memory area of at
least (n + 4) bytes (see example).

Example

The program reads a floating-point value x, converts it as specified in n, and outputs it as a
string to the char array buf. The malloc function is used to reserve (n + 4) bytes.

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  double x;
  int n;
  char *buf;
  printf("Please enter floating-point number: \n");
  if ( scanf("%lf",&x) == 1)
  {
    printf("How many significant digits : \n");
    if ( scanf("%d",&n) == 1)
    {
      buf = (char *)malloc(n + 4);
      printf("After conversion, the number is :  %s \n", gcvt(x, n, buf));
    }
  }
  return 0;
}

See also

ecvt, gcvt