Reputation: 23
I have a double whose value i get dynamically and the value is 0.94289988675 and also i get a another double whose value is 0.94289988777 .I just need to compare the two values. But it says they are not same. How can i compare till first four digits of those values.
Code:
for (z = 0; z < something.Count(); z++)
{
if (largest == Math.Round(0.94289988675 [z],4))
{
//proceed
}
}
largest = 0.94289988675 0.94289988675[z] comes 0.94289988777. z is.
It does not go in the loop. Please help me out.
Upvotes: 1
Views: 6362
Reputation: 273219
How can i compare till first four bits
I assume you mean 4 digits, not 4 bits.
Just take the Absolute value of the difference:
if (Math.Abs(largest - 0.94289988675) < 0.0001)
{
//proceed
}
Equality is a pretty difficult concept with floating point types, never use the simple ==
Upvotes: 10
Reputation: 77294
You never test floating point values for equality. Ever. In any programming language. The most common way to handle this is to subtract one from the other and compare this difference to a small number commonly called Epsilon. In your case 0.001 for the first four digits might be appropriate. If the difference of both numbers is smaller than your Epsilon value, they are considered equal.
double x = ?;
double y = ?;
double epsilon = 0.001;
var difference = Math.Abs(x - y);
var isEqual = difference < espilon;
Please note that you should not use the constant Double.Epsilon
for this. That's just bad naming, it's for something completely unrelated.
Upvotes: 7