Question

Possible Duplicate:
Does setprecision in c++ round? If so why am I seeing this?

Here is the function I'm using

char* round(double value, int decimal_places)
{
decimal_places = decimal_places+1;
std::stringstream s2;
   s2 << std::setprecision(decimal_places) << std::setiosflags(std::ios_base::fixed) << value;
std::string st = s2.str();
  return st;
}

My input value is 0.89425 and the number of decimal palaces is 4

My output is 0.8942 but i want 0.8943 i.e., if next digit after my required decimal places is >= 5 then the output should be rounded to the next value.

Was it helpful?

Solution

0.89425 is not representable exactly in binary floating point; the nearest exactly representable value is 0.894249999999999989341858963598497211933135986328125, which is correctly rounded to decimal 0.8942.

If you want to see decimal rounding behaviour, use fixed-point or decimal floating point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top