8 December 2011

How to compare two floats values

This note is for myself.

For some reason i keep forgot about this very useful method :(
To compare 2 floats value  use method from Float class:
Float.compare(floatVariable1,floatVariable2);

Example:

float floatVariable1 = 8.88f;
float floatVariable2 = 1.14f;

int result = Float.compare(floatVariable1, floatVariable2);

if (result > 0) {
      System.out.println(floatVariable1 + " is grater than " + floatVariable2);
} else if (result == 0) {
      System.out.println(floatVariable1 + " and " + floatVariable2 + " are equal");
} else {
      System.out.println(floatVariable2 + " is grater than " + floatVariable1);
}

No comments:

Post a Comment