c++ - Casting floating point (double) to string -


i'm running i've never seen before , understand going on. i'm trying round double 2 decimal places , cast value string. upon completion of cast things go crazy on me.

here code:

void formatpercent(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; } 

i wasn't getting quite expected did investigation. did following:

std::cout << std::setprecision(10) << "number = " << number << std::endl; std::cout << "percent = " << percent << std::endl; 

...and following:

number = 30.63 percent = 30.629999999999999 

i suspect boost doing funny. have insight here?

seriously, how strange this?!? ask 10 digit precision on double , 4 digits. ask cast 4 digits string , mess. going on?

std::precision sets maximum number of significant digits display

on default floating-point notation, precision field specifies maximum number of meaningful digits display in total counting both before , after decimal point. notice not minimum , therefore not pad displayed number trailing zeros if number can displayed less digits precision.

30.629999999999999 floating point representation of 30.63


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 -