PatchworkOS
Loading...
Searching...
No Matches
atof.c
Go to the documentation of this file.
1#include <ctype.h>
2#include <stdbool.h>
3#include <stdlib.h>
4
5// TODO: Finish this implementation, missing NAN, INF 0x/0X handling.
6
7double atof(const char* nptr)
8{
9 double result = 0.0;
10 double fraction = 0.0;
11 double divisor = 1.0;
12 int exponent = 0;
13 bool isNegative = false;
14 bool hasExponent = false;
15 bool isExponentNegative = false;
16
17 while (isspace((unsigned char)*nptr))
18 {
19 nptr++;
20 }
21
22 if (*nptr == '+')
23 {
24 nptr++;
25 }
26 else if (*nptr == '-')
27 {
28 nptr++;
29 isNegative = true;
30 }
31
32 while (*nptr >= '0' && *nptr <= '9')
33 {
34 result = result * 10.0 + (*nptr - '0');
35 nptr++;
36 }
37
38 if (*nptr == '.')
39 {
40 nptr++;
41
42 while (*nptr >= '0' && *nptr <= '9')
43 {
44 fraction = fraction * 10.0 + (*nptr - '0');
45 divisor *= 10.0;
46 nptr++;
47 }
48
49 result += fraction / divisor;
50 }
51
52 if (*nptr == 'e' || *nptr == 'E')
53 {
54 nptr++;
55 hasExponent = true;
56
57 if (*nptr == '+')
58 {
59 nptr++;
60 }
61 else if (*nptr == '-')
62 {
63 nptr++;
64 isExponentNegative = true;
65 }
66
67 while (*nptr >= '0' && *nptr <= '9')
68 {
69 exponent = exponent * 10 + (*nptr - '0');
70 nptr++;
71 }
72 }
73
74 if (hasExponent)
75 {
76 double power = 1.0;
77 for (int i = 0; i < exponent; i++)
78 {
79 power *= 10.0;
80 }
81
82 if (isExponentNegative)
83 {
84 result /= power;
85 }
86 else
87 {
88 result *= power;
89 }
90 }
91
92 return isNegative ? -result : result;
93}
double atof(const char *nptr)
Definition atof.c:7
_PUBLIC int isspace(int c)
Definition isspace.c:5