File: strtod.c

package info (click to toggle)
starplot 0.95.5-8.2%2Bdeb9u1
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 3,476 kB
  • sloc: ansic: 11,296; cpp: 6,418; sh: 5,092; makefile: 613; yacc: 289; sed: 16
file content (74 lines) | stat: -rw-r--r-- 1,570 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "compat.h"
#include <ctype.h>

#if ! HAVE_STRTOD

static double pow10(int power)
{
  int i;
  double result = 1.0, multiplier = 10.0;

  if (power < 0) { multiplier = 0.1; power *= -1; }
  for (i = 0; i < power; i++) { result *= multiplier; }

  return result;
}
	
double
strtod(const char *nptr, char **endptr)
{
  int i = 0, neg = 0;
  double result = 0;
  
  if (nptr == 0) return 0.0;

  while (isspace(nptr[i])) i++;
  if (nptr[i] == '-') neg = 1;
  else if (! isdigit(nptr[i]) && nptr[i] != '+') {
    /* "If no conversion is performed, zero is returned and the value
     * of nptr is stored in the location referenced by endptr." */
    if (endptr) *endptr = nptr;
    return result;
  }

  if (nptr[i] == '-' || nptr[i] == '+') i++;
  while (isdigit(nptr[i])) {
    result *= 10;
    result += (nptr[i] - '0');
    i++;
  }

  /* check for decimal places */
  if (nptr[i] == ',' || nptr[i] == '.') {
    double fractional = 0.0;
    int decimal_pt = i;
    i++;
    while (isdigit(nptr[i])) {
      fractional += (nptr[i] - '0') * pow10(decimal_pt - i);
      i++;
    }
    result += fractional;
  }
  
  /* check for exponent */
  if (nptr[i] == 'e' || nptr[i] == 'E') {
    int exponent = 0, expneg = 0;
    i++;
    if (nptr[i] == '-') { expneg = 1; i++; }
    if (nptr[i] == '+') i++;
    while (isdigit(nptr[i])) {
      exponent *= 10;
      exponent += (nptr[i] - '0');
      i++;
    }
    if (expneg) exponent *= -1;
    result *= pow10(exponent);
  }
  
  if (neg) result *= -1;
  if (endptr) *endptr = nptr + i;
  return result;
}

#endif