Skip to content

Commit 3d2121f

Browse files
committed
update: 优化tofloat方法使其节省空间, close #32
1 parent 0bca71a commit 3d2121f

File tree

2 files changed

+41
-5
lines changed

2 files changed

+41
-5
lines changed

cores/AirMCU/WString.cpp

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -890,10 +890,46 @@ float String::toFloat(void) const
890890
return float(toDouble());
891891
}
892892

893-
double String::toDouble(void) const
894-
{
895-
if (buffer) {
896-
return atof(buffer);
893+
float String::toDouble(void) const
894+
{
895+
if (buffer)
896+
{
897+
char *p = buffer;
898+
float f = 0.0;
899+
int i = -1;
900+
// 分割一下字符串
901+
if (p[0] != '\0') // 小数点不在开头
902+
{
903+
i = 0;
904+
while (p[i] != '\0')
905+
{
906+
if (p[i] == '.')
907+
{
908+
p[i] = '\0';
909+
i++;
910+
break;
911+
}
912+
i++;
913+
}
914+
f += atol(p);
915+
}
916+
else // 开头是小数点
917+
{
918+
i = 1;
919+
}
920+
if (i != -1) // 有小数点
921+
{
922+
int p_sum = strlen(p + i);
923+
float f2 = atol(p + i);
924+
while (p_sum--)
925+
f2 /= 10.0;
926+
f += f2;
927+
}
928+
else // 没有小数点
929+
{
930+
f = atol(p);
931+
}
932+
return f;
897933
}
898934
return 0;
899935
}

cores/AirMCU/WString.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ class String {
271271
// parsing/conversion
272272
long toInt(void) const;
273273
float toFloat(void) const;
274-
double toDouble(void) const;
274+
float toDouble(void) const;
275275

276276
protected:
277277
char *buffer; // the actual char array

0 commit comments

Comments
 (0)