Comparing BigDecimal and int in Java

23,156

Solution 1

If you expect the BigDecimal value to be really big (i.e. outside the range of int values, which is -231 to 231-1) and/or to contain decimal digits, or simply want to play safe, you should convert the int to BigDecimal to avoid overflow / truncation errors.

Otherwise, if performance is a really big issue (which is rare), it might be better the other way around.

Solution 2

You want to convert the int to a BigDecimal.

This is because you won't always be able to convert a BigDecimal to an int; you'll lose any information after the decimal point and the value of the BigDecimal might be outside the range of an int.

Solution 3

As BigDecimal extends the range of int you will have to convert the int into BigDecimal to be sure they can be compared, anyhow.

Share:
23,156
HighBit
Author by

HighBit

Updated on July 19, 2022

Comments

  • HighBit
    HighBit almost 2 years

    Which one is the best way of comparing a BigDecimal and an int in Java : coverting the BigDecimal to int or converting int to BigDecimal ?

  • Oliver Charlesworth
    Oliver Charlesworth about 12 years
    Why would this be "throwing garbage on the heap"?
  • nist
    nist about 12 years
    but this might couse a overflow and the result might be wrong. If BigDecimal bd = maxint +1 and bd are converted to int the result will be 1
  • Bober02
    Bober02 about 12 years
    Sure, it depends on the actual use Case. @Oli each time for the comparison case you would create a new BigInteger object, which might not be necessary and which resides on the heap, instead of taking the actual primitive value already stored within the BigInt object itself
  • HighBit
    HighBit about 12 years
    Thats exactly what I wanted to know ! Thanks @peter !