Search code examples
c++stringc++11floating-pointfloating-point-conversion

Parse and convert denorm numbers?


In C++, we can store denorm numbers into variables without problems:

double x = std::numeric_limits<double>::denorm_min();

Then, we can print this variable without problems:

std::cout<<std::setprecision(std::numeric_limits<double>::max_digits10)
std::cout<<std::scientific;
std::cout<<x;
std::cout<<std::endl;

And it will print:

4.94065645841246544e-324

But a problem occurs when one tries to parse this number. Imagine that this number is stored inside a file, and read as a string. The problem is that:

std::string str = "4.94065645841246544e-324";
double x = std::stod(str);

will throw an std::out_of_range exception.

So my question is: how to convert a denorm value stored in a string?


Solution

  • I'm not sure I have understood the problem, but using std::istringstream like this:

    std::string str = "4.94065645841246544e-324";
    double x;
    std::istringstream iss(str);
    iss >> x;
    std::cout << std::setprecision(std::numeric_limits<double>::max_digits10);
    std::cout << std::scientific;
    std::cout << x << std::endl;
    

    ...gives me:

    4.94065645841246544e-324