/*
* A function to convert a string into a float
* Author: Danny Battison
* Contact: gabehabe@hotmail.com
*/
#include
float StringToFloat (std::string str)
{
float total = 0; // the total to return
int length = str.length(); // the length of the string
int prefixLength=0; // the length of the number BEFORE the decimal
int suffixLength=0; // the length of the number AFTER the decimal
bool decimalFound = false; // use this to decide whether to increment prefix or suffix
for (unsigned int i = 0; i < str.length(); i++)
{ // loop through the string
if (str[i] == '.')
{ // if we found the '.' then we are now counting how long the decimal place is
length --; // subtract one from the length (. isn't an integer!)
decimalFound = true; // we found the decimal! HAZAA!
}
else if (!decimalFound)
prefixLength++;// if the decimal still hasn't been found, we should count the main number
else if (decimalFound) // otherwise, we should count how long the decimal is!
suffixLength++;
}
int x = 1; // our multiplier, used for thousands, hundreds, tens, units, etc
for (int i = 1; i < prefixLength; i++)
x *= 10;
for (int i = 0; i < prefixLength; i++)
{ // get the integer value
// 48 is the base value (ASCII)
// multiply it by x for tens, units, etc
total += (static_cast
x /= 10; // divide to decide which is the next unit
}
float decimal=0; // our value of the decimal only (we’ll add it to total later)
x = 1; // again, but this time we’ll go the other way to make it all below 0
for (int i = 1; i < suffixLength; i++)
x *= 10;
for (int i = 0; i < suffixLength; i++)
{ // same again, but this time it's for the decimal value
decimal += (static_cast
x /= 10;
}
for (int i = 0; i < suffixLength; i++)
decimal /= 10; // make the decimal so that it is 0.whatever
total += decimal; // add them together
return total;
}
/** EXAMPLE USAGE **/
#include
int main ()
{
std::string str = “123.456”;
float f = StringToFloat(str) + 0.2f; // to get 123.656
std::cout << f;
std::cin.get ();
return EXIT_SUCCESS;
}