c-strtod.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Convert string to double, using the C locale.
  2. Copyright (C) 2003, 2004, 2006 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. /* Written by Paul Eggert. */
  14. #include <config.h>
  15. #include "c-strtod.h"
  16. #include <locale.h>
  17. #include <stdlib.h>
  18. #include "xalloc.h"
  19. #if LONG
  20. # define C_STRTOD c_strtold
  21. # define DOUBLE long double
  22. # define STRTOD_L strtold_l
  23. #else
  24. # define C_STRTOD c_strtod
  25. # define DOUBLE double
  26. # define STRTOD_L strtod_l
  27. #endif
  28. /* c_strtold falls back on strtod if strtold doesn't conform to C99. */
  29. #if LONG && HAVE_C99_STRTOLD
  30. # define STRTOD strtold
  31. #else
  32. # define STRTOD strtod
  33. #endif
  34. DOUBLE
  35. C_STRTOD (char const *nptr, char **endptr)
  36. {
  37. DOUBLE r;
  38. #ifdef LC_ALL_MASK
  39. locale_t c_locale = newlocale (LC_ALL_MASK, "C", 0);
  40. r = STRTOD_L (nptr, endptr, c_locale);
  41. freelocale (c_locale);
  42. #else
  43. char *saved_locale = setlocale (LC_NUMERIC, NULL);
  44. if (saved_locale)
  45. {
  46. saved_locale = xstrdup (saved_locale);
  47. setlocale (LC_NUMERIC, "C");
  48. }
  49. r = STRTOD (nptr, endptr);
  50. if (saved_locale)
  51. {
  52. setlocale (LC_NUMERIC, saved_locale);
  53. free (saved_locale);
  54. }
  55. #endif
  56. return r;
  57. }