Search code examples
c++floating-pointfstreamifstream

Reading floating point values from a file drops all or part of the decimal part


I need to read floating-point values from a file.

Basic sample code of how I do this:

int main() 
{
    float number;
    ifstream inputFile;

    inputFile.open("testfile.dat");

    inputFile >> number;

    cout << number << endl;

    return 0;
}

The first line in the file is: 13212.13131. But when I cout 'number' the displayed number is: 13212.1

The problem is part of the decimal gets dropped and in other cases all of it gets dropped. Why does this happen, and how can I solve this problem?

The point of reading the number from the file is to do mathematical calculations with it.


Solution

  • First, floating-point precision on output (for both std::cout and printf) is 6 decimal digits by default. You need std::setprecision() to get it print more digits. But you'll then get to the limit of float type.

    On most systems float is IEEE-754 single precision, therefore it can only store about 7 digits of significant. The nearest to 13212.13131 is 1.3212130859375E4. If you need more precision, you must use double, which has about 15-16 digits of precision on most systems.

    Read more: Is floating point math broken?