I'm trying to round doubles to a specific precision, however the following functions give me different results:
Version 1:
static double RoundPrecision(double& val)
{
val = floor(val * 1000 + 0.5) * 0.001;
return val;
}
Version 2:
static double RoundPrecision(double& val)
{
val = floor(val * 1000 + 0.5) / 1000;
return val;
}
Example output when rounding the number 300.9:
- Version 1: 300.90000000000003
- Version 2: 300.89999999999998
Both versions sometimes give the same result, but for specific inputs the results differ. I have to have consistent behavior when equating numbers to other variables in the program.
EDIT:
I am aware of the problems with floating point precision, which is exactly what I'm trying to avoid here by rounding. I need a consistent way to round to 3 decimal point precision.