Reputation: 2113
I am using the following code to convert input strings to floats:
template <typename T>
T parseString(const std::string &s)
{
T val;
std::istringstream is(s.c_str());
is >> val;
return val;
}
float x = parseString<float>("0.1");
std::cout << std::setprecision(12) << x;
When I print x I get "0.10000000149" which is obviously wrong. Any thoughts?
Upvotes: 0
Views: 87
Reputation: 111389
The single-precision float data type is precise to about 8-9 decimal digits. You are printing it with 12 digits, so you can expect the last three to be off.
The reason why there's any difference at all is that 1/10 cannot be represented exactly as a binary fraction; there are dozens of questions with great answers on this site about this issue. The single-precision value closest to 1/10 is exactly 0.100000001490116119384765625.
Upvotes: 2