String to decimal conversion
From CodeCodex
A lot of languages have this sort of conversion built in, but for various reasons you might need this algorithm on your own. This algorithm takes a string as an input and returns its value as a decimal.
[edit] Algorithm
- Let f be the floating point number to be returned, initially 0
- Let s be the string
- Let c be the current position, initially the beginning of the string
- Let l be the length of the string
- Let n be the negative multiplier, initially equal to 1
- If s(c) is -, let n be -1
- While s(c) is not . AND c is less than l AND s(c) is a valid digit
- Let f be (f * 10) + the digit's value
- Advance c
- If s(c) is a decimal point
- Advance c
- While c is less than l AND s(c) is a valid digit
- Let f be f + (the digit's value / 10)
- Advance c
- return f * n
[edit] C
/* NOTE: The function has a length parameter. Why? Substrings. Using a function like this allows you to apply the technique to a C-style string (either by manually figuring out the length or by using strlen) as well as a substring of a C-style string. Therefore this function will get the float value of "123.45" correctly, even if it was part of a substring "(123.45,678.90]" (as it will be in the C version of the Within Range function)
- /
float GetFloat(const char *str, unsigned int len)
{
unsigned int i = 0;
int neg = 0;
float number = 0;
float mult = 1;
if (str[i] == '-')
{
neg = 1;
i++;
}
while (i < len && str[i] >= '0' && str[i] <= '9')
{
number = number * 10;
number = number + str[i] - '0';
i++;
}
if (i < len && str[i] == '.')
i++;
while (i < len && str[i] >= '0' && str[i] <= '9')
{
mult = mult / 10;
number = number + (str[i] - '0') * mult;
i++;
}
if (neg)
number = -number;
return number;
}

