Java BigDecimal 4 Basics: Warning, Casting, Simple Math & Comparison
2 min readApr 21, 2024
1. Warning : Only Declaring BigDecimal with String
It is very easy to mistakenly declare like this
// Incorrect
new BigDecimal(100.11)
// This is correct
new BigDecimal("100.11")
It MUST BE STRING
You can check this quickly with jshell
2. Casting the Unknown Type to BigDecimal
Compare to the known type of Long
, Float
new BigDecimal(longValue)
BigDecimal.valueOf(longValue)
Casting BigDecimal
can be problematic when type is unknown.
Example when this happen is when the nativeQuery=true
from Spring JPA and want to cast it as BigDecimal
.
Here is the solution.
// Object[] result
BigDecimal(result[1].toString())
3. How to do the Basic Math
The basic math will become harder to read
BigDecimal b1 = new BigDecimal("532.12");
BigDecimal b2 = new BigDecimal("123.21");
b1.add(b2)
b1.subtract(b2)
b1.multiply(b2)
b1.divide(b2, 2, RoundingMode.HALF_EVEN)
Chaining is possible
b1.add(b2).multiply(b2).subtract(b1).divide(b2, 4, RoundingMode.HALF_EVEN)
4. How to do the Comparison
The basic comparison will move to the right and always set the rightmost with 0
value
b1.compareTo(b2) < 0 // "<"
b1.compareTo(b2) > 0 // ">"
b1.compareTo(b2) == 0 // "=="
b1.compareTo(b2) != 0 // "!="
b1.compareTo(b2) >= 0 // ">="
b1.compareTo(b2) <= 0 // "<="
If you try and see the comparison result, you will see something like this
Then it is why you will then compare it with 0