Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing BigDecimal and int in Java

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 ?

like image 431
HighBit Avatar asked Mar 18 '12 16:03

HighBit


People also ask

How does BigDecimal compare to int?

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.

Is BigDecimal an integer?

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.


1 Answers

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.

like image 65
Péter Török Avatar answered Oct 02 '22 15:10

Péter Török