Compare 2 doubles, but without all digits on C

I want to compare 2 double, but without all digits. for example, I have this double 1.548799778 and this 1.547990978, and I want to compare 1.xx from each. How can I get around this double to 1.xx ?? Thanks

+5
source share
7 answers

One method will use the function truncas follows:

double d1, d2;
d1 = 1.548799778;
d2 = 1.547990978;
if (trunc(d1*100) == trunc(d2*100)) {
   // do your thing
}

Use 100because you want two decimal places. You can use other numbers if you want more or less decimal places.

+5
source

to compare that xand yare close enough, something like

(x==0.0 && y==0.0) || fabs(x-y)/max(fabs(x),fabs(y))<1e-6

x floor(x) ceil(x),

: , NaN ( )

+4

- .

 if (fabs(a - b) <= tolerance) { .... }

, .

, 0,001 .

+2

floor ceil math.h

0

.

if (  x-y < 0.01 && x-y > -0.01 )
0

Math.h

double check(double number)
{
    if (modf(number, 0) >= .5)
        return number >= 0 ? ceil(number) : floor(number);
    else
        return number < 0 ? ceil(number) : floor(number);
}

double round(double number, unsigned int places)
{
    double off = pow(10, places);
    return check(number * off) / off;
}

if(round(1.548799778, 2) == round(1.547990978, 2))
{
}
0

.

int compare(double a, double b)
{
    static const double PRECISION = 0.0001;
    if (a < b)
        return b - a < PRECISION ? 0 : 1;
    else
        return a - b < PRECISION ? 0 : -1;
}
0

All Articles