String Tokenizer -- nextDouble()
This is a method within a class I wrote that is used to split up a string into tokens given the delimeter. I wanted functionality similiar to the Java equivelant.
PHP Code:
/**
* Get the next double token -- descructive
* @return double - The double returned
* @throw - NumberFormatException
*/
double StringTokenizer::nextDouble()
{
string strToken = next();
if (!strToken.empty()) {
istringstream dblCheckStream(strToken);
double dValue = 0.0;
if (dblCheckStream >> dValue) {
return dValue;
} else {
m_strData = strToken + m_strData;
throw(NumberFormatException("The next token does not contain a correct double value!"));
}
}
return 0.0;
}
Now the output is not as expected:
When the string "34.21249" is read out as a double I get 34.2125
Wow, look at the rounding... It rounds any number with more than 4 decimal places, it rounds to the 4rth decimal place.
Is there perhaps a more accurate way of parsing a double out of a string?
Edit:
Actually looking at the numbers through a debugger it seems nothing is accurate:
"12.5644" = 12.564399999999999
"34.21249" = 34.21249000000003
"56.000005" = 56.000005000002
Re: String Tokenizer -- nextDouble()
Because of the way doubles and floats are stored, this inaccuracy past certain decimal places is unavoidable. That's why when comparing floating point values, it is often best to not do direct equality, but rather check if the difference is smaller than a given value.
Re: String Tokenizer -- nextDouble()
So this behaviour is normal then?
Unavoidable.
Thanks,
Halsafar
Re: String Tokenizer -- nextDouble()
the culprit is most likey the function that converts the float to string. while in memory the float is correct, it appears incorrect because it gets rounded when you convert it back to text. try this:
Code:
double hey = atof("34.2124956");
if (hey == 34.2124956) // the value was parsed correctly, it's 34.2124956
cout << hey; // outputs 34.2125, which would appear to be wrong
else
cout << "no";
Re: String Tokenizer -- nextDouble()
Or use the setprecision() output modifier to increase output precision.
Re: String Tokenizer -- nextDouble()
I use:
istringstream dblCheckStream(strToken);
double dValue = 0.0;
dblCheckStream >> dValue
To parse the double, this same method also works for ints. Could this be causing any more problems?
SetPrecision, would that just allow me greater accuracy with less decimal points?