Merge from coreutils.
[gnulib.git] / lib / xstrtod.c
1 /* error-checking interface to strtod-like functions
2
3    Copyright (C) 1996, 1999, 2000, 2003, 2004 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 /* Written by Jim Meyering.  */
20
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #include "xstrtod.h"
26
27 #include <errno.h>
28 #include <limits.h>
29 #include <stdio.h>
30
31 /* Tell the compiler that non-default rounding modes are used.  */
32 #if 199901 <= __STDC_VERSION__
33  #pragma STDC FENV_ACCESS ON
34 #endif
35
36 /* An interface to strtod that encapsulates all the error checking
37    one should usually perform.  Like strtod, but upon successful
38    conversion put the result in *RESULT and return true.  Return
39    false and don't modify *RESULT upon any failure.  CONVERT
40    specifies the conversion function, e.g., strtod itself.  */
41
42 bool
43 xstrtod (char const *str, char const **ptr, double *result,
44          double (*convert) (char const *, char **))
45 {
46   double val;
47   char *terminator;
48   bool ok = true;
49
50   errno = 0;
51   val = convert (str, &terminator);
52
53   /* Having a non-zero terminator is an error only when PTR is NULL. */
54   if (terminator == str || (ptr == NULL && *terminator != '\0'))
55     ok = false;
56   else
57     {
58       /* Allow underflow (in which case strtod returns zero),
59          but flag overflow as an error. */
60       if (val != 0.0 && errno == ERANGE)
61         ok = false;
62     }
63
64   if (ptr != NULL)
65     *ptr = terminator;
66
67   *result = val;
68   return ok;
69 }