Any suggestion on determining a double is not zero?
if(value != 0) //divide by value is safe when value is not exactly zero. Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0. Save this answer.
Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result. For this reason, we must use a more complex comparison algorithm.
// assuming employeeSalary is a double if(Double. compare(employeeSalary, Double. valueOf(0.0)) > 0 ){ // Employee salary is greater than zero. } else{ // Employee salary is less than or equal to zero. }
You have to set an epsilon that is compatible with the problem you are solving. Then, you could use something like
bool DoubleEquals(double value1, double value2)
{
return Math.Abs(value1 - value2) < epsilon;
}
EDIT
Since you asked a way to determine if a double is not zero, you could use this function by writing:
if (!DoubleEquals(value, 0)) { /* do your not zero things */ }
I felt this method was better because it's more general purpose.
Hi depends on what sort of calculations you are doing. Some times you get a very small number which is close to 0 but not quite
I usually do
if (Math.Abs(MyNumber) < 1e-10)
Hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With