Comparing BigDecimal and int in Java
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.
HighBit
Updated on July 19, 2022Comments
-
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 about 12 yearsWhy would this be "throwing garbage on the heap"?
-
nist about 12 yearsbut 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 about 12 yearsSure, 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 about 12 yearsThats exactly what I wanted to know ! Thanks @peter !