-3

I am stuck up with this problem.
I get double values in some variables which are as follows:

a = 0.76271469999999997000
b = 0.66698279999999999000
c = 0.34262199999999998000

I need to round these to

rounded_a = 0.762714700000000
rounded_b = 0.666982800000000
rounded_c = 0.342622000000000

How should I go about doing this?

Alastair Pitts
  • 19,423
  • 9
  • 68
  • 97
VirajP
  • 91
  • 1
  • 5

2 Answers2

0
#include <stdio.h>
#include <math.h>

double round_n(double x, int n){
    double wk;
    wk = pow(10.0, (double)n);
    return round(x * wk)/wk;//c99 function
}

int main(void){
    double a, b, c;
    a = 0.76271469999999997000;
    b = 0.66698279999999999000;
    c = 0.34262199999999998000;
    a = round_n(a, 7);
    b = round_n(b, 7);
    c = round_n(c, 7);
    printf("a=%.8lf\nb=%.8lf\nc=%.8lf", a, b, c);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
-1

Here is the code I use:

int64_t __pow10_arr[18] = { 1l, 10l, 100l, 1000l, 10000l, 100000l,
                            1000000l, 10000000, 100000000l, 1000000000l, 10000000000l, 100000000000l,
                            1000000000000l, 10000000000000l, 100000000000000l, 1000000000000000l, 10000000000000000l, 100000000000000000l };

double roundToNfractions ( double val, int n )
{
  if (n<0 || n >= ( sizeof (__pow10_arr)/ sizeof (int64_t) ) ) {
    // log error however you wish to
    return val;
  }
  val *= __pow10_arr[n];
  val += 0.5;
  val = (uint64_t) val;
  val /= __pow10_arr[n];
  return val;
}
Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • 1
    Can you guarantee the values he wants are even directly representable in binary floating point? I would suggest he tries to understand floating point better to realize he either needs to use something else or adjust his approach. – xaxxon Jun 04 '13 at 07:27
  • and why on earth would you multiply it by 10? You're very likely to lose precision. – xaxxon Jun 04 '13 at 07:29
  • The only reasonable approach I can think of is to print out the value and handle it as a text processing problem. But you're still likely to have problems if you try to put it back into a double from a string. – xaxxon Jun 04 '13 at 07:31
  • 1
    @xaxxon I guarantee nothing, **I answered the question**. That's the idea of StackOverflow. Place for your first comment is in his question, not my answer. As for the code: it works. It is reasonably quick. The loss of precision is possible, but is almost impossible where I use this code. I don't know if it can be used where he needs it, but that's not up to me to decide. You can process it as a string, but that would cause some problems on it's own and would probably be slower. – Dariusz Jun 04 '13 at 07:36