3

In my Linq query I have a where statement that looks like this

&& vio.Bows.Any(nw => nw.XCoordinate.Equals(currVio.XCoordinate)))

values are

nw.XCoordinate = 4056.48751252685
currVio.XCoordinate = 4056.488

Thus the statement of Equals is not working, what is the easiest way to round?

public double XCoordinate { get; set; }
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • You could not simply use Equals to compare two double number. Check this question: http://stackoverflow.com/questions/1398753/comparing-double-values-in-c-sharp – 2power10 May 23 '13 at 01:53

2 Answers2

3

You can use the usual way of comparing double for proximity by calculating the absolute difference, and comparing it to a small value:

Math.Abs(x - y) < 1E-8 // 1E-8 is 0.00000001

For example, you can use this approach in a LINQ query like this:

&& vio.Bows.Any(nw => Math.Abs(nw.XCoordinate-currVio.XCoordinate) < 0.001)
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You could also use Math.Round i.e.:

double x = 4056.48751252685;
var newx = Math.Round(x,3);

So if you knew you always wanted 3 decimal places you could:

&& vio.Bows.Any(nw => Math.Round(nw.XCoordinate,3).Equals(math.Round(currVio.XCoordinate,3))))

You could go further and implement IEquetable, and override the equals function, determine which of the two values has the least number of decimal places, round both to that value and compare.

Squid
  • 4,560
  • 1
  • 12
  • 8