I have a problem getting a correct/accurate string representation of float/double/long double values.
I have this function that attempts to get a string representation of a floating point value:
template <typename T>
std::string double_to_string(const T& v) {
static_assert(std::is_floating_point<T>::value,
"T is not a floating point type");
std::stringstream sstr;
sstr.setf(std::ios::fixed | std::ios::showpoint);
sstr << v << std::ends;
return sstr.str();
}
I invoke it with float, double and long double values, but do not get a correct/accurate string representation of the actual value I pass in to the function:
// float:
std::cout << double_to_string(77777777777777.7777777f) << std::endl;
// double:
std::cout << double_to_string(77777777777777.7777777) << std::endl;
// long double:
std::cout << double_to_string(77777777777777.7777777L) << std::endl;
The output I get is as below:
// float:
77777780867072.000000
// double:
77777777777777.781250
// long double:
77777777777777.777779
Is there any way I can get an accurate string representation of float/double/long double values in C++?
(p.s. I'm using g++ 7.2.0)
Thanks.