1

I have a code in which i am comparing a float with == operator

String sFloat = "0.0";
float n = Float.parseFloat(sFloat);
System.out.println("n--"+n);
if(n == 0){
    System.out.println("inside if");
}
else{
    System.out.println("inside else");
}

is the above way is the right to compare float or it will fail in other case . like .equals or any other method .

float is a primitive variable not Float

I do not want to use wrapper Float. I want only the primitive comparision

SarthAk
  • 1,628
  • 3
  • 19
  • 24
  • This question is matching: [whats wrong with using to compare floats in java](http://stackoverflow.com/questions/1088216/whats-wrong-with-using-to-compare-floats-in-java). A quote from that answer _Floating point values can be off by a little bit, so they may not report as exactly equal. For example, setting a float to "6.1" and then printing it out again, you may get a reported value of something like "6.099999904632568359375". This is fundamental to the way floats work; therefore, you don't want to compare them using equality, but rather comparison within a range_ – uniknow Apr 07 '16 at 07:16
  • That is already mentioned "float is a primitive variable not Float" why duplicated ? – SarthAk Apr 07 '16 at 07:44

3 Answers3

2

Primitive variables are compared with == operator not with equals() method, since it is used for only reference type variables.

Areca
  • 1,292
  • 4
  • 11
  • 21
1
 float f1 = 22.30f;
 float f2 = 88.67f;
 int retval = Float.compare(f1, f2);

 if(retval > 0) {
    System.out.println("f1 is greater than f2");
 }
 else if(retval < 0) {
    System.out.println("f1 is less than f2");
 }
 else {
    System.out.println("f1 is equal to f2");
 }

That would be the best way to compare float values.

Praveen Kumar
  • 1,515
  • 1
  • 21
  • 39
  • 1
    I believe this will have some unexpected functionality when -0.0 is compared to 0.0 (and some others such cases). Of course, it depends on what specific comparison you want to achieve. – Teemu Ilmonen Apr 07 '16 at 07:32
1

As you have said, float is a primitive variabile, so it's safe to use the == operator to compare floats. In addition, using Float, the class wrapper of the float type, you should use the equals() method provider.

Ilario Pierbattista
  • 3,175
  • 2
  • 31
  • 41