strtod.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * strtod.c - This file is part of the libc-8086 package for ELKS,
  3. * Copyright (C) 1995, 1996 Nat Friedman <ndf@linux.mit.edu>.
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Library General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library 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 GNU
  13. * Library General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Library General Public
  16. * License along with this library; if not, write to the Free
  17. * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  18. *
  19. */
  20. #include <stdlib.h>
  21. #include <ctype.h>
  22. float strtod(const char *nptr, char **endptr)
  23. {
  24. unsigned short negative;
  25. float number;
  26. float fp_part;
  27. int exponent;
  28. unsigned short exp_negative;
  29. /* advance beyond any leading whitespace */
  30. while (isspace(*nptr))
  31. nptr++;
  32. /* check for optional '+' or '-' */
  33. negative = 0;
  34. if (*nptr == '-') {
  35. negative = 1;
  36. nptr++;
  37. } else if (*nptr == '+')
  38. nptr++;
  39. number = 0;
  40. while (isdigit(*nptr)) {
  41. number = number * 10 + (*nptr - '0');
  42. nptr++;
  43. }
  44. if (*nptr == '.') {
  45. nptr++;
  46. fp_part = 0;
  47. while (isdigit(*nptr)) {
  48. fp_part = fp_part / 10.0 + (*nptr - '0') / 10.0;
  49. nptr++;
  50. }
  51. number += fp_part;
  52. }
  53. if (*nptr == 'e' || *nptr == 'E') {
  54. nptr++;
  55. exp_negative = 0;
  56. if (*nptr == '-') {
  57. exp_negative = 1;
  58. nptr++;
  59. } else if (*nptr == '+')
  60. nptr++;
  61. exponent = 0;
  62. while (isdigit(*nptr)) {
  63. exponent = exponent * 10 + (*nptr - '0');
  64. exponent++;
  65. }
  66. }
  67. while (exponent) {
  68. if (exp_negative)
  69. number /= 10;
  70. else
  71. number *= 10;
  72. exponent--;
  73. }
  74. return (negative ? -number : number);
  75. }