c++ - Round Double and Cast to String -


i suppose question follow previous question had regarding casting double string.

i have api i'm given string represents number. need round number 2 decimals of precision , return string. attempt 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 0 total.";         throw std::runtime_error(err.str());     }     number = (number/config.total)*100;     // format string return 2 decimals of precision     number = floor(number*100 + .5)/100;     percent = boost::lexical_cast<std::string>(number);      return; } 

unfortunately cast captures "unrounded" values. (i.e. number = 30.63, percent = 30.629999999999) can suggest clean way round double , cast string 1 naturally want?

thanks in advance help. :)

streams usual formatting facility in c++. in case, stringstream trick:

std::ostringstream ss; ss << std::fixed << std::setprecision(2) << number; percent = ss.str(); 

you familiar setprecision previous post. fixed here used make precision affect number of digits after decimal point, instead of setting number of significant digits whole number.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -