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

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
Asked:
rohgan
1 Solution
 
AxterCommented:
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
 
Kent OlsenData 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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