1

Given a float, I want to round the result to 4 decimal places using half-even rounding, i.e., rounding to the next even number method. For example, when I have the following code snippet:

#include <iostream>
#include <iomanip>

int main(){
    float x = 70.04535; 
    std::cout << std::fixed << std::setprecision(4) << x << std::endl;
}

The output is 70.0453, but I want to be 70.0454. I could not find anything in the standard library, is there any function to achieve this? If not, what would a custom function look like?

Sleik
  • 341
  • 4
  • 11

2 Answers2

2

If you use float, you're kind of screwed here. There is no such value as 70.04535, because it's not representable in IEEE 754 binary floating point.

Easy demonstration with Python's decimal.Decimal class, which will try to reproduce the actual float (well, Python float is a C double, but it's the same principle) value out to 30 digits of precision:

>>> import decimal
>>> decimal.Decimal(70.04535)
Decimal('70.0453499999999991132426657713949680328369140625')

So your actual value doesn't end in a 5, it ends in 49999... (the closest to 70.04535 a C double can get; C float is even less precise); even banker's rounding would round it down. If this is important to your program, you need to use an equivalent C or C++ library that matches "human" (base-10) math expectations, e.g. libmpdec (which is what Python's decimal.Decimal uses under the hood).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

I'm sure someone can improve this, but it gets the job done.

double round_p( double x, int p ){                                        
    double d = std::pow(10,p+1);                                          
    return ((x*d)+5)/d;                                                   
}                                                                         
void main(int argc, const char**argv){                                    
    double x = 70.04535;                                                  
    {                                                                     
        std::cout << "value " << x << " rounded " << round_p(x,4) << std::endl;
        std::cout << "CHECK " << (bool)(round_p(x,4) == 70.0454) << std::endl; 
    }                                                                     
}