Is it OK to compare a float variable with 0 i.e if (float_var ==
0.0)?If it is not correct please let me know how to compare float
variable with 0.
It depends on how you calculated the float variable and why you are
comparing it to zero. Floating point calculations are often subject
to roundoff error. An expression like (10.0*0.1 - 1.0) is likely
to *NOT* come out exactly zero.
If the floating point variable got the value 0.0 because you assigned
the constant 0.0 to it, or you fed the text "0.0" into strtod() or
[sf]scanf() as a marker for the end of the data, you are likely
safe. The float variable will likely have exactly zero in it. On
the other hand, if you have calculated it by subtracting two numbers
that ought to be equal, you may not get exactly zero when you
mathematically would expect to.
There are two commonly used methods of comparing two floating point
variables for equality. One tests if they are equal within a certain
amount. The other tests if they are equal within a certain percentage.
The percentage method doesn't work too well if the value you are
comparing against is zero (division by zero or nearly zero tends
not to work well).
Generally, which method you use and how you figure the threshhold
should be determined by what the numbers represent, *NOT* the
characteristics of the floating point numbers. For example, in the
USA, you might omit sending out a bill if the amount due is within
half a cent of zero. (Presuming here you ARE supposed to send out
notices of credit balances). The "half a cent" number is determined
by the fact that there aren't any coins smaller than a cent, and
anything less than half a cent would be rounded to zero. It has
nothing to do with how many bits there are in a floating point
number.
(I prefer to use integer quantities of cents (or whatever currency)
and explicitly round to the nearest cent where necessary. Sometimes
the law (e.g. that governing sales tax) has peculiar laws about
rounding unlike any conventional methods of rounding.)
You might check whether two voltages are "equal enough" by testing
if they are within 2% of each other. The reason you might choose
2% is because that is the accuracy specification of the meter you
are using to measure voltages.
Gordon L. Burditt