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 ?
Use the compareTo method of BigDecimal : public int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal. Returns: -1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.
A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With