I have a string that stores a decimal value, for instance, "0.10". I want to convert this to a float. But when I use atof to do it, the number I get is not exactly the value it should be. I'm writing some complicated algorithms involving some number crunching of decimal values, so this is throwing my final results off.
Here is some simple code that describes the problem I'm having. Here, I simply put a decimal value into a string, convert it to a float with atof, and print it out with cout. The result I'm getting shows that atof is adding a tiny decimal number to the final value.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string value = "0.10";
float valueAsFloat = atof(value.c_str());
cout.precision(20);
cout << valueAsFloat << endl;
return 0;
}
The output is:
0.10000000149011611938
Any ideas? I'm using the GNU g++ compiler on Ubuntu. Could it be a bug with this compiler that's causing the problem? If so, is there any other way to convert the value to a float and get the right value? Thanks.
Edit: While that question gives a partial explanation as to why this happens, it does not give a full value, and it only offers a single solution which may or may not work. Therefore, I thinking leaving this question open as a separate question is valid.