• Post Reply Bookmark Topic Watch Topic
  • New Topic

Checking for zero value ?  RSS feed

 
Amandeep Singh
Ranch Hand
Posts: 853
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I have these two methods available for checking whether it is zero or not.
which one is preferred or any new approach ?

I will prefer 1st if condition method.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neither. Comparing a double to another double via == is unreliable. What if it is ".00000001"? It's better to do:
bd.doubleValue() - 0 < .0001 // or however much granularity you want

or:
BigDecimal.ZERO.equals(bd);
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne Boyarsky wrote:or:
BigDecimal.ZERO.equals(bd);

Output: false. This is because, scientifically speaking, 0 != 0.0.

prints 0 though, so that would be a possibility.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:Output: false. This is because, scientifically speaking, 0 != 0.0.


I was also surprised (a long while back), when I learned of this. It does seem weird.

Henry
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scientifically speaking, 0 can be any value between -0.5 (exclusive) and 0.5 (inclusive), whereas 0.0 can be any value between -0.05 (exclusive) and 0.05 (exclusive). If you take this into account it makes a bit more sense.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
Rob Prime wrote:Output: false. This is because, scientifically speaking, 0 != 0.0.


I was also surprised (a long while back), when I learned of this. It does seem weird.

Henry

Interesting. Now I have to make sure I don't have this bug in any of my code!
 
Amandeep Singh
Ranch Hand
Posts: 853
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This already i learned from Rob in previous posts.

So the correct solution will be to use this code:

 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!