In my company's code, they use double.tryParse()
which is quite good but sets too much security for our needs. As we sometimes have to parse a few billion strings, I came up with this code which is a little bit faster (10%) but I have the feeling that it's not at its best... Unfortunately, this kind of stuff require more knowledge than I have.
private static double GetDoubleValue(string input)
{
double n = 0;
int decimalPosition = input.Length;
bool separatorFound = false;
bool negative = input[0] == '-';
for (int k = (negative ? 1 : 0); k < input.Length; k++)
{
char c = input[k];
if (c == '.' || c == ',')
{
if (separatorFound)
return Double.NaN;
decimalPosition = k + 1;
separatorFound = true;
}
else
{
if (!char.IsDigit(c))
return Double.NaN;
n = (n * 10) + (c - '0');
}
}
return ((negative ? -1 : 1) * n) / CustomPow(10, input.Length - decimalPosition);
}
private static double CustomPow(int num, int exp)
{
double result = 1.0;
while (exp > 0)
{
if (exp%2 == 1)
result *= num;
exp >>= 1;
num *= num;
}
return result;
}