Casting to string

I'm running into something I've never seen before and would very much like to understand what is going on. I'm trying to round a double to 2 decimal places and cast that value to a string. Upon completion of the cast things go crazy on me.

Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 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;
}


I wasn't getting quite what I expected so I did some investigation. I did the following:

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


...and get the following:

1
2
number = 30.63
percent = 30.629999999999999


I suspect that boost is doing something funny. Does anyone have any insight here?

Seriously, how strange is this?!? I ask for 10 digit precision on a double and get 4 digits. I ask to cast those 4 digits to a string and get that mess. What is going on?
Last edited on
I realize the issue is coming from the fact that std::precision does not show trailing zeros or 9s.

Therefore the cast is working correctly. :)
Topic archived. No new replies allowed.