0

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;
}
Rick
  • 353
  • 1
  • 16
  • *I've been looking into rounding doubles by a specified decimal place in C++.* -- Simple response -- don't waste your time. Use another data type that supports exact math. Either use all integer or a third-party arbitrary precision or big integer type. -- *I've found a way to accomplish exactly* -- If you have, write a paper and show your findings to various organizations. It would be worth the read. – PaulMcKenzie May 12 '18 at 18:23
  • Use GMP rationals, not any kind of float. – o11c May 12 '18 at 18:27

0 Answers0