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.

Algorithm[edit]

  1. Let f be the floating point number to be returned, initially 0
  2. Let s be the string
  3. Let c be the current position, initially the beginning of the string
  4. Let l be the length of the string
  5. Let n be the negative multiplier, initially equal to 1
  6. If s(c) is -, let n be -1
  7. While s(c) is not . AND c is less than l AND s(c) is a valid digit
    1. Let f be (f * 10) + the digit's value
    2. Advance c
  8. If s(c) is a decimal point
    1. Advance c
  9. While c is less than l AND s(c) is a valid digit
    1. Let f be f + (the digit's value / 10)
    2. Advance c
  10. return f * n

C[edit]

/* 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;
 }