Commit 97402ab3 by malcolm

Added atof

parent bb652938
Showing with 49 additions and 0 deletions
...@@ -108,3 +108,51 @@ int stoi(char *str) ...@@ -108,3 +108,51 @@ int stoi(char *str)
return sign*res; return sign*res;
} }
double atof(char* num)
{
if (!num || !*num)
return 0;
double integerPart = 0;
double fractionPart = 0;
int divisorForFraction = 1;
int sign = 1;
bool inFraction = false;
if (*num == '-')
{
++num;
sign = -1;
}
else if (*num == '+')
{
++num;
}
while (*num != '\0')
{
if (*num >= '0' && *num <= '9')
{
if (inFraction)
{
fractionPart = fractionPart*10 + (*num - '0');
divisorForFraction *= 10;
}
else
{
integerPart = integerPart*10 + (*num - '0');
}
}
else if (*num == '.')
{
if (inFraction)
return sign * (integerPart + fractionPart/divisorForFraction);
else
inFraction = true;
}
else
{
return sign * (integerPart + fractionPart/divisorForFraction);
}
++num;
}
return sign * (integerPart + fractionPart/divisorForFraction);
}
...@@ -9,4 +9,5 @@ int strcmp(const char* s1, const char* s2); ...@@ -9,4 +9,5 @@ int strcmp(const char* s1, const char* s2);
int strncmp(const char* s1, const char* s2, size_t n); int strncmp(const char* s1, const char* s2, size_t n);
int atoi(char *p); int atoi(char *p);
int stoi(char* str); int stoi(char* str);
double atof(char* num);
#endif #endif
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment