c-strtod.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 2, or (at your option)
  6. 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, write to the Free Software Foundation,
  13. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  14. /* Written by Paul Eggert. */
  15. #include <config.h>
  16. #include "c-strtod.h"
  17. #include <locale.h>
  18. #include <stdlib.h>
  19. #include "xalloc.h"
  20. #if LONG
  21. # define C_STRTOD c_strtold
  22. # define DOUBLE long double
  23. # define STRTOD_L strtold_l
  24. #else
  25. # define C_STRTOD c_strtod
  26. # define DOUBLE double
  27. # define STRTOD_L strtod_l
  28. #endif
  29. /* c_strtold falls back on strtod if strtold doesn't conform to C99. */
  30. #if LONG && HAVE_C99_STRTOLD
  31. # define STRTOD strtold
  32. #else
  33. # define STRTOD strtod
  34. #endif
  35. DOUBLE
  36. C_STRTOD (char const *nptr, char **endptr)
  37. {
  38. DOUBLE r;
  39. #ifdef LC_ALL_MASK
  40. locale_t c_locale = newlocale (LC_ALL_MASK, "C", 0);
  41. r = STRTOD_L (nptr, endptr, c_locale);
  42. freelocale (c_locale);
  43. #else
  44. char *saved_locale = setlocale (LC_NUMERIC, NULL);
  45. if (saved_locale)
  46. {
  47. saved_locale = xstrdup (saved_locale);
  48. setlocale (LC_NUMERIC, "C");
  49. }
  50. r = STRTOD (nptr, endptr);
  51. if (saved_locale)
  52. {
  53. setlocale (LC_NUMERIC, saved_locale);
  54. free (saved_locale);
  55. }
  56. #endif
  57. return r;
  58. }