Chapter Contents

Previous

Next
atof

atof



Convert a String to Floating Point

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
DIAGNOSTICS
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <stdlib.h>

double atof(const char *p);


DESCRIPTION

atof converts the character string p to a double-precision, floating-point number after skipping any leading white space (such as blanks, tabs, and new-line characters). The conversion stops at the first unrecognized character.

The argument string may contain a decimal point and may be followed by an e or an E and a signed integer exponent. A leading minus sign indicates a negative number. White space is not allowed between the minus sign and the number or between the number and the exponent.


RETURN VALUE

atof returns a value of type double . If no initial segment of the string is a valid number, the return value is 0.


DIAGNOSTICS

No indication is returned to the program to specify whether the string contains a valid number, so you should validate the string before calling atof .

If the floating-point value is outside the range of valid 370 floating-point numbers, ± HUGE_VAL is returned if the correct value is too large, or 0.0 if the correct value is too close to 0.


EXAMPLE

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

main() {
   char input[80];
   int int_format;
   long int_value;
   double dbl_value;

   puts("Enter a valid C numeric constant (without any suffixes)");
   gets(input);
      /* If there's a decimal point, it's a double.   */
   if (strchr(input, '.')) int_format = 0;
      /* If it starts 0x, it's an integer.            */
   else if((input[0] == '0' && tolower(input[1]) == 'x') ||
           ((input[0] == '+' || input[0] == '-') &&
            input[1] == '0' && tolower(input[2]) == 'x'))
      int_format = 1;
      /* If it has an E and isn't hex, it's a double. */
   else if (strpbrk(input, "eE")) int_format = 0;
     /* Doubles must have either "." or "e".          */
   else int_format = 1;

      /* Convert to integer (errors ignored).         */
   if (int_format) {
      int_value = strtol(input, NULL, 0);
      printf("Your input appears to be the integer %d\n", 
            int_value);
   }
      /* Convert to double (errors ignored).          */
   else {
      dbl_value = atof(input);
      printf("Your input appears to be the double %.16g\n", 
            dbl_value);
   }
   exit(0);
}


RELATED FUNCTIONS

strtod


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.