Can the standard library to_string function work for the smallest floating point values?

Viewed 83

A simple experiment using to_string with the minimum floating point values, results in 0.0000 for both float and double types:

std::to_string(std::numeric_limits<float>::min());
std::to_string(std::numeric_limits<double>::min());

The correct answer would be, e.g. 1.17549e-38 for the float type. Is this a known limitation of std::to_string or am I doing something wrong? Is there a way around this, so that I can get the correct result?

1 Answers

You need to use oss instead of std::to_string in C++. Main reason is to_string makes prediction using std::fixed parameter.

Simply your code needs to look like this:

#include <iostream>
#include <limits>
#include <string>
#include <sstream>
int main()
{
    //std::cout << std::numeric_limits<float>::min() << std::endl;
    //std::cout << std::numeric_limits<double>::min() << std::endl;
    std::ostringstream out;
    out << std::numeric_limits<float>::min();
    std::cout << out.str() << std::endl;
    out << std::numeric_limits<double>::min();
    std::cout << out.str() << std::endl;
    return 0;
}


Related