Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing Floats

 
L. Riley
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you compare Floats to Floats (wrapper classes)? Some books I've read say always use .equal'. One says that in comparing Floats, "= =" is the same as '.equal'.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Easy enough to test:

Do they both give the same answer? If not, which one gives teh result you want when comparing two Floats with the same wrapped value?
 
Zakaria Haque
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by liz riley:
How do you compare Floats to Floats (wrapper classes)? Some books I've read say always use .equal'. One says that in comparing Floats, "= =" is the same as '.equal'.

According to javadoc api spec
"Note that in most cases, for two instances of class Float, f1 and f2, the value of f1.equal.(f2) is true if and only if f1.floatValue() == f2.floatValue()"
 
Sayed Ibrahim Hashimi
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When comparing Objects you want to use the .equals(..) method. Because when you do == that is checking to see if the references are the same not wether they are storing the same values.
Hope this helps.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When comparing Objects you want to use the .equals(..) method. Because when you do == that is checking to see if the references are the same not wether they are storing the same values.


If you are referring to f1==f2 that is certainly correct, but the Float wrapper class has a method called floatValue() which returns the corresponding primitive of a Float, in which case, f1.floatValue()==f2.floatValue() is also appropriate for comparing Floats.
-anthony
 
Thomas Smets
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Anthony Villanueva:

If you are referring to f1==f2 that is certainly correct, but the Float wrapper class has a method called floatValue() which returns the corresponding primitive of a Float, in which case, f1.floatValue()==f2.floatValue() is also appropriate for comparing Floats.
-anthony


Which is probably what the equals () does !
Thomas,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic