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




Reply With Quote