EDITED to add value invoking errno == ERANGE;
, below for illustration
First, in your post you indicated you tried:
char * num1 = "12.2";
double numD1 = atof(num1);
This should have worked.
The simplest method is: (as you have already tried)
double x = atof("12.2");
atof()- Converts the initial portion of a string to a double representation.
Better would be:
double x = strtod("12.3", &ptr);
strtod():
The C library function double strtod(const char *str, char **endptr)
converts the string pointed to by the argument str
to a floating-point
number (type double
). If endptr
is not NULL
, a pointer to the
character after the last character used in the conversion is stored in
the location referenced by endptr
. If strtod()
could not convert the string because the correct value is outside the range of representable values, then it sets errno
to ERANGE
(defined in errno.h
).
Here is an example of using strtod();
with two inputs: (also illustrates use of errno
)
#include <errno.h>
int main ()
{
char input[] = "10.0 5.0";
char bad1[] = "0.3e500";
char bad2[] = "test";
char *ptr;
double a, b, c;
errno = 0;
a = strtod (input,&ptr);
if(errno != ERANGE)
{
errno = 0;
b = strtod (ptr,0);
if(errno != ERANGE)
{
printf ("a: %*.2lf\nb: %*.2lf\nQuotient = %*.2lf\n", 12, a, 12, b, 3, a/b);
}else printf("errno is %d\n", errno);
} else printf("errno is %d\n", errno);
//bad numeric input
errno = 0;
c = strtod (bad1, &ptr);
if(errno != ERANGE)
{
printf ("Output= %.2lf\n", c);
} else printf("errno is %d\n", errno);
//text input
errno = 0;
c = strtod (bad2, &ptr);
if(ptr != bad2)
{
printf ("Output= %.2lf\n", c);
} else printf("invalid non-numeric input: \"%s\" \n", ptr);
getchar();
return 0;
}