Skip to content

Commit eeabbf4

Browse files
committed
Add atof implementation
Fix #27
1 parent 940d009 commit eeabbf4

File tree

2 files changed

+48
-6
lines changed

2 files changed

+48
-6
lines changed

hardware/esp8266com/esp8266/cores/esp8266/WString.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -702,12 +702,12 @@ void ICACHE_FLASH_ATTR String::trim(void)
702702

703703
long ICACHE_FLASH_ATTR String::toInt(void) const
704704
{
705-
if (buffer) return atol_internal(buffer);
705+
if (buffer) return atol(buffer);
706706
return 0;
707707
}
708708

709709
float ICACHE_FLASH_ATTR String::toFloat(void) const
710710
{
711-
if (buffer) return float(atof_internal(buffer));
711+
if (buffer) return atof(buffer);
712712
return 0;
713713
}

hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_noniso.c

+46-4
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
#define sprintf ets_sprintf
2727
#define strcpy ets_strcpy
2828

29-
long atol_internal(const char* s)
29+
long atol(const char* s)
3030
{
3131
int result = 0;
3232
int i;
@@ -44,10 +44,52 @@ long atol_internal(const char* s)
4444
return sign * result;
4545
}
4646

47-
float atof_internal(const char* s)
47+
// Source:
48+
// https://github.com/anakod/Sming/blob/master/Sming/system/stringconversion.cpp#L93
49+
double atof(const char* s)
4850
{
49-
float result = 0;
50-
return result;
51+
double result = 0;
52+
double sign = 1;
53+
54+
while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
55+
++s;
56+
57+
if (*s == 0)
58+
return 0;
59+
60+
if (*s == '-')
61+
{
62+
sign = -1;
63+
++s;
64+
}
65+
if (*s == '+')
66+
{
67+
++s;
68+
}
69+
70+
bool decimals = false;
71+
double factor = 1.0;
72+
char c;
73+
while((c = *s))
74+
{
75+
if (c == '.')
76+
{
77+
decimals = true;
78+
++s;
79+
continue;
80+
}
81+
82+
int d = c - '0';
83+
if (d < 0 || d > 9)
84+
break;
85+
86+
result = 10.0 * result + d;
87+
if (decimals)
88+
factor *= 0.1;
89+
++s;
90+
}
91+
92+
return result * factor;
5193
}
5294

5395

0 commit comments

Comments
 (0)