I've been looking into rounding doubles by a specified decimal place in C++. I've found a way to accomplish exactly that, but it seems to be slightly off. There is a small imprecision tacked on to the end of the rounded value.
Here's a sample program I made to show the problem... In this example, the value 0.929383191 should be rounded to 0.929 (or at least 0.92900000000000000). However, I am getting a value of 0.92900000000000005. Which is a fairly insignificant difference, but I'd like it to be precise. Is that possible?
#include "stdafx.h"
#include <math.h>
// round float to n decimals precision
const double RoundToNearestDecimalPlace(
double value,
int decimal_place)
{
if (value == 0.0)
return 0.0;
double factor = pow(10.0, decimal_place - ceil(log10(fabs(value))));
return round(value * factor) / factor;
}
int main()
{
const double Result = RoundToNearestDecimalPlace(0.929383191, 3);
return 0;
}