-6

I know there're already a lot of questions like this. But what if I need to compare 2 Numbers and I don't know what types they are. Which means one of them could be Float and another one be Long. Are there some libs in JavaCore or Apache that can solve this issue (unfortunalety NumberUtils lacks this method)? I've been looking for a few hours but haven't succeeded. Or I should reinvent the wheel with something like this. I just don't believe that such high-level language like Java doesn't have tools to compare 2 numbers.

Community
  • 1
  • 1
deathangel908
  • 5,954
  • 6
  • 31
  • 62

2 Answers2

0

You can use the doubleValue() method on both numbers and then compare the double values.

If you need a higher precision for integers, you can implement this as sepcial case.

If you have objects that are not an instance of Number (e.g. Object or String containing a "number"), then you should throw all your code away and start from scratch, honestly.

UniversE
  • 2,172
  • 13
  • 19
0

The int will be converted to a long before the compare is made. In principle a cast will take place, like

if (a == (long)b)

Java will cast primative types for you, provided that it does not involve a loss of precision. Since a long can hold all the values an int can, the cast will be performed automatically, but you would have to explicitly cast (for example) a long if you wanted to use it where an int should be.

edit: to cast a long "x" to an int, use: x = (int)x;

Masood
  • 471
  • 5
  • 10