I have a string
strValue = "11.900000"
I want to parse it to a float value. So I tried:
float fValue = -1;
sscanf_s(strValue.c_str(), "%f", &fValue);
try
{
double test = std::stod(strValue, &sz);
fValue = (float) std::stod(strValue, &sz);
}
catch (...)
{
fValue = -1;
}
For double
it is accurate:
test = 11.900000000000000
For float
it is inaccurate:
fValue = 11.8999996
Is there a possibility to do this accurately? (I know there is a inaccuracy while working with floats, but is there a better way to do it?)
The value
11.8999996
is the most precise approximation of11.9
that can be represented by thefloat
type.