Is it safe to compare C# doubles or floats against assigned, default values?
For example:
public class Foo
{
private double defaultEfficiency = 100.0;
public double efficiencyBar = defaultEfficiency;
public bool IsBarAtDefaultValue()
{
if(efficiencyBar == defaultEfficiency)
return true;
else
return false;
}
}
So my question is if the check within IsBarAtDefaultValue()
is going to work as I expect it to? ie. It will return true
if efficiencyBar
is the same as defaultEfficiency
.
This SO question: Is it safe to check floating ... asks about a specific case when the default value is 0.0. My question concerns the broader case of any default value.
To provide a more concrete example...
I am working on an application that deals with motor efficiencies which are generally in the range of 0 - 100%, or 0.0 to 1.0. The user has the ability to define new motors and assign various efficiencies.
In the panel to define a new motor, I want to populate the various efficiencies with default values. Later on, I want to check and see if the user altered the value to something other than the default. For example, I want to check and see if they made changes but accidentally forgot to save their work.
That led to my wondering about what value is actually used in the assignment of a default value for floating point types (double & float). The linked SO question discusses the 0.0 case, but I wondered about the broader (not 0.0) case as I don't want to use 0.0 for the default values for the efficiencies.