Damian
Damian

Reputation: 4631

convert from string to double fails to convert as expected

I am trying to convert "21898.99" to a string I but keep on getting 21898.990000000002 but I am expecting 21898.99

#include <cstdlib>
#include <boost/lexical_cast.hpp>
#include <limits>
#include <iostream>
int main()
{
    double d1 = std::strtod("21898.99", nullptr);
    long double d2 = std::strtold("21898.99", nullptr);
    float d3 = std::strtof("21898.99", nullptr);

    double d4 = atof("21898.99");

    double d5 = boost::lexical_cast<double>("21898.99");

    double d6;  
    sscanf_s("21898.99", "%lf", &d6);

    double d7;
    sscanf_s("21898.99", "%lg", &d7);

    std::istringstream ss("21898.99");
    double d8 = 0.0;
    ss >> d8;

    typedef std::numeric_limits< double > dbl;
    std::cout.precision(dbl::max_digits10);
    std::cout << d1 << "\n";
    std::cout << d2 << "\n";
    std::cout << d3 << "\n";
    std::cout << d4 << "\n";
    std::cout << d5 << "\n";
    std::cout << d6 << "\n";
    std::cout << d7 << "\n";
    std::cout << d8 << "\n"; 
}

Output:

21898.990000000002
21898.990000000002
21898.990234375
21898.990000000002
21898.990000000002
21898.990000000002
21898.990000000002
21898.990000000002

Windows 10 version 10.0.14939.0
Visual Studio 2017 15.9.0, C++ 19.15.26732.1
Windows SDK 10.0.17134.0

I tried on a centos machine with gcc and this call works, but the others also fail.
long double d2 = std::strtold("21898.99", nullptr); since it returns 21898.99

Upvotes: 2

Views: 61

Answers (1)

Tordek
Tordek

Reputation: 10872

This is the expected behavior for floating point numbers; some values are not exactly representable.

Upvotes: 1

Related Questions