0

how can i round number on 5 decimal numbers of some result ? I have something like this...

double s;
s=d/a;s1=d1/a1;
here i need to round these 2 numbers ... because s1 is different from s by 0.00000002 etc
if(s1>s){
printf("S1 > S");
    if(s1==s){
printf("S1 = S");

someone with help with this ? Thank you

blackroad
  • 29
  • 1
  • 5
  • Possible duplicate of [What is the best way to compare floats for almost-equality in Python?](http://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python) – woockashek Nov 19 '16 at 19:45

1 Answers1

0

Round numbers before (compare) statement

Scale by 100,000, round to a whole number and then compare.

No need to divide by the scaling and introduce more computational errors in order to compare.

#include <math.h>
int compare_rounded(double a, double b, double scale) {
  // or use round(), nearby()
  a = rint(a*scale);
  b = rint(b*scale);   
  return (a > b) - (a < b);   
}

OR perhaps more simply subtract. This gives slight different results. All depends what OP wants.

int compare_rounded2(double a, double b, double guard) {
  double diff = a-b;
  if (diff < -guard) return -1;
  return diff > guard;
}

then call one of the 2

double s  =d/a; 
double s1 =d1/a1;
int cmp = compare_rounded(s1,s, 100000.0);
// or 
int cmp = compare_rounded2(s1,s, 100000.0);
if (cmp > 0) {
  puts("S1 > S");
} else if (cmp == 0) {
  puts("S1 == S");
} else {
  puts("S1 < S");
}

To cope with both numbers near the same limit of double like DBL_MAX, additional code is needed is the first function due to a*scale overflow.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256