0

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.

A. Duff
  • 4,097
  • 7
  • 38
  • 69

1 Answers1

1

This is not an issue with the conversion activity, but the inherent precision (or lack of precision) of the float. Different compilers will have different precision. Also, as you perform more and more mathematical operations in serial where the output of one is the input into the next, the precision is further eroded. The lack of precision comes from using binary (discrete) data to approximate values in the continuous real number set.

You may choose to use a "double" instead, and traditionally it has double the precision of a float. However, some modern compilers use the same precision for "double" as float.

The issue can be reduced by choosing different compilers, different data types, but the ultimate problem will remain.

M. K. Hunter
  • 1,778
  • 3
  • 21
  • 27
  • 1
    Different compilers are unlikely to help, as they'll be constrained by the underlying CPU architecture. Most use [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). – Mark Ransom May 29 '14 at 22:42