Code: Select all
float stringToFloat(std::string str, float defaultVal = 0)
{
float decimal = 0;
int integer = 0;
int sign = 1;
for (int i = str.size()-1; i >= 0; i--)
{
int digit = (int)str[i] - 48;
if (digit >= 0 && digit < 10)
{
decimal+=digit;
if (decimal != 0)
decimal/=10;
}
else if (str[i] == '.')
{
for (int j = 0; j < i; j++)
{
int digit = (int)str[j] - 48;
if (digit >= 0 && digit < 10)
{
integer*=10;
integer+=digit;
}
else if (str[j] == '-') sign = -1;
else return defaultVal; // Remove this line to find a number in a string with characters.
}
return (decimal+(float)integer) * sign;
}
else return defaultVal; // Remove this line to find a number in a string with characters.
}
return defaultVal;// Remove this line to find a number in a string with characters.
}