• Status: Solved
• Priority: Medium
• Security: Public
• Views: 250

# How to Check if double is zero?

I have a variable:

double aVar;

aVar can have any value such as 0.0, 0.000, 0.0007,0.0000003

How can I check if it is zero?

"If (aVar ==0)" does not seem to work
0
rohgan
1 Solution

Commented:
Hi rohgan,
A double and a float are not exact numbers.
You can check to see if the number is between a given range that is close to zero.

if (aVar < 0.000001f && aVar > 0.000000f)

David Maisonave :-)
Cheers!
0

Data Warehouse Architect / DBACommented:
Hi rohgan,

Actually, the statement:

if (aVar == 0)

DOES check that the value is zero.  Unfortunately, the inherent error in floating point math algorithms sometimes results in answers that are "almost zero" instead of zero.  (It's kind of like being almost dead or almost pregnant.)  But in C, you have to deal with it.

Axter gives you a pretty good handle on how to test for "almost zero".  You can also write it as a macro, which can make your code easier to read.

#define isfpzero(a) (a < 0.000001f && a > -0.000001f : 1 : 0)

if (isfpzero(aVar))
printf ("Floating Point Zero");
else
printf ("Non Zero");

Good Luck!
Kent
0

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.