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?
If you use
float, you're kind of screwed here. There is no such value as70.04535, because it's not representable in IEEE 754 binary floating point.Easy demonstration with Python's
decimal.Decimalclass, which will try to reproduce the actualfloat(well, Pythonfloatis a Cdouble, but it's the same principle) value out to 30 digits of precision:So your actual value doesn't end in a 5, it ends in 49999... (the closest to
70.04535a Cdoublecan get; Cfloatis 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'sdecimal.Decimaluses under the hood).