Skip to content

Instantly share code, notes, and snippets.

@markpapadakis
Created May 5, 2015 21:43
Show Gist options
  • Save markpapadakis/82a7880bd72f6ca53912 to your computer and use it in GitHub Desktop.
Save markpapadakis/82a7880bd72f6ca53912 to your computer and use it in GitHub Desktop.
double AsDouble(const char *p, const uint32_t len)
{
const char *it = p, *const e = p + len;
double sign;
if (it == e)
return 0;
else if (*it == '-')
{
++it;
sign = -1;
}
else if (unlikely(*it == '+'))
{
++it;
sign = 1;
}
else
sign = 1;
double v{0};
do
{
if (*it == '.' || *it == ',') // support both radix characters
{
double exp{0};
double pow10{1.0};
for (++it; it != e; ++it)
{
if (likely(isdigit(*it)))
{
exp = exp * 10 + (*it- '0');
pow10*=10.0;
}
else
return NAN;
}
return (v + (exp * (1.0L / pow10))) * sign;
}
else if (likely(isdigit(*it)))
v = v * 10 + (*(it++) - '0');
else
return NAN;
} while (it != e);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment