I want to stringify a fraction of unsigned integers in C++ with variable precision. So 1/3
would be printed as 0.33
using a precision
of 2
. I know that float
and std::ostream::precision
could be used for a quick and dirty solution:
std::string stringifyFraction(unsigned numerator,
unsigned denominator,
unsigned precision)
{
std::stringstream output;
output.precision(precision);
output << static_cast<float>(numerator) / denominator;
return output.str();
}
However, this is not good enough because float
has limited precision and can't actually represent decimal numbers accurately. What other options do I have? Even a double
would fail if I wanted 100 digits or so, or in case of a recurring fraction.