Search code examples
c++precisioniomanip

set precision return statement C++


I want to return a double from a function with a set precision! It is that possible ? I want an accuracy of 10-5 !

For example :

double f(double a ,double b)
{
  //something like return.setprecision(6); 
  return (a+b)/2;
}

Solution

  • Assuming you mean truncated to 5 decimals:

    Multiply by 105. Round to integer. Divide result by 105.

    For the rounding, use the standard library so that you avoid exceeding the range of an integer type.


    Note that the result can only be perfect for numbers that can be exactly represented. The common representations of floating point numbers are binary, although the C++ standard allows decimal representations. And that means that with most numbers the result will not be exact.