home *** CD-ROM | disk | FTP | other *** search
/ PC Extra Super CD 1998 January / PCPLUS131.iso / DJGPP / V2 / DJLSR201.ZIP / src / libc / ansi / stdlib / strtod.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-08-31  |  1.5 KB  |  98 lines

  1. /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
  2. /* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */
  3. #include <math.h>
  4. #include <stdlib.h>
  5. #include <libc/unconst.h>
  6.  
  7. double
  8. strtod(const char *s, char **sret)
  9. {
  10.   long double r;        /* result */
  11.   int e;            /* exponent */
  12.   long double d;        /* scale */
  13.   int sign;            /* +- 1.0 */
  14.   int esign;
  15.   int i;
  16.   int flags=0;
  17.  
  18.   r = 0.0;
  19.   sign = 1;
  20.   e = 0;
  21.   esign = 1;
  22.  
  23.   while ((*s == ' ') || (*s == '\t'))
  24.     s++;
  25.  
  26.   if (*s == '+')
  27.     s++;
  28.   else if (*s == '-')
  29.   {
  30.     sign = -1;
  31.     s++;
  32.   }
  33.  
  34.   while ((*s >= '0') && (*s <= '9'))
  35.   {
  36.     flags |= 1;
  37.     r *= 10.0;
  38.     r += *s - '0';
  39.     s++;
  40.   }
  41.  
  42.   if (*s == '.')
  43.   {
  44.     d = 0.1L;
  45.     s++;
  46.     while ((*s >= '0') && (*s <= '9'))
  47.     {
  48.       flags |= 2;
  49.       r += d * (*s - '0');
  50.       s++;
  51.       d *= 0.1L;
  52.     }
  53.   }
  54.  
  55.   if (flags == 0)
  56.   {
  57.     if (sret)
  58.       *sret = unconst(s, char *);
  59.     return 0;
  60.   }
  61.  
  62.   if ((*s == 'e') || (*s == 'E'))
  63.   {
  64.     s++;
  65.     if (*s == '+')
  66.       s++;
  67.     else if (*s == '-')
  68.     {
  69.       s++;
  70.       esign = -1;
  71.     }
  72.     if ((*s < '0') || (*s > '9'))
  73.     {
  74.       if (sret)
  75.     *sret = unconst(s, char *);
  76.       return r;
  77.     }
  78.  
  79.     while ((*s >= '0') && (*s <= '9'))
  80.     {
  81.       e *= 10;
  82.       e += *s - '0';
  83.       s++;
  84.     }
  85.   }
  86.  
  87.   if (esign < 0)
  88.     for (i = 1; i <= e; i++)
  89.       r *= 0.1L;
  90.   else
  91.     for (i = 1; i <= e; i++)
  92.       r *= 10.0;
  93.  
  94.   if (sret)
  95.     *sret = unconst(s, char *);
  96.   return r * sign;
  97. }
  98.