I suppose this question is a follow up to a previous question I had regarding casting a double to a string.
I have an API where I’m given a string which represents a number. I need to round this number to 2 decimals of precision and return it as a string. My attempt to do this follows:
void formatPercentCommon(std::string& percent, const std::string& value, Config& config)
{
double number = boost::lexical_cast<double>(value);
if (config.total == 0)
{
std::ostringstream err;
err << "Cannot calculate percent from zero total.";
throw std::runtime_error(err.str());
}
number = (number/config.total)*100;
// Format the string to only return 2 decimals of precision
number = floor(number*100 + .5)/100;
percent = boost::lexical_cast<std::string>(number);
return;
}
Unfortunately the cast captures “unrounded” values. (i.e. number = 30.63, percent = 30.629999999999) Can anyone suggest a clean way to round a double and cast it to a string so I get what one would naturally want?
Thanks in advance for the help. 🙂
Streams are the usual formatting facility in C++. In this case, a stringstream will do the trick:
You are probably already familiar with
setprecisionfrom your previous post.fixedhere is used to make the precision affect the number of digits after the decimal point, instead of setting the number of significant digits for the whole number.