Question

I want to compare two doubles a and b in C# (where for example b has more decimal places) in the way that: if I round the number b to number of decimal places of a i should get the same number if they are the same. Example:

double a = 0.123;
double b = 0.1234567890;

should be same.

double a = 0.123457
double b = 0.123456789

should be same.

I cannot write

if(Math.Abs(a-b) < eps)

because I don't know how to calculate precision eps.

Was it helpful?

Solution

If I have understood what you want you could just shift the digits before the decimal place til the "smaller" (i.e. one with least significant figures) is a integer, then compare: i.e. in some class...

static bool comp(double a, double b)
{
    while((a-(int)a)>0 && (b - (int)b)>0)
    {
        a *= 10;
        b *= 10;
    }
    a = (int)a;
    b = (int)b;
    return a == b;
}

Edit

Clearly calling (int)x on a double is asking for trouble since double can store bigger numbers than ints. This is better:

while((a-Math.Floor(a))>0 && (b - Math.Floor(b))>0)
//...

OTHER TIPS

double has epsilon double.Epsilon or set prefer error by hardcode, f.e. 0.00001

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top