I have BiGDecimal price
and i need to check if it is in some range.
For example should be 3 conditions:
if (price >= 0 and price <=500) {
....
} else if (price >=500 && price <=1000) {
....
} else if (price > 1000) {
....
}
How to do it right using BigDecimal type.
A BigDecimal consists of a random precision integer unscaled value and a 32-bit integer scale. If greater than or equal to zero, the scale is the number of digits to the right of the decimal point. If less than zero, the unscaled value of the number is multiplied by 10^(-scale).
Using the compareTo Method Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. Therefore, we can check BigDecimal. ZERO. compareTo(givenBdNumber) == 0 to decide if givenBdNumber has the value zero.
compareTo(BigDecimal bg) method checks for equality of this BigDecimal and BigDecimal object bg passed as parameter. The method considers two equal BigDecimal objects even if they are equal in value irrespective of the scale.
If your main goal is validating BigDecimal dataType for nulls, then just make a comparison; yourBigDecimal != null. The above statement is enough for comparison and checking.
Lets make it generic:
public static <T extends Comparable<T>> boolean isBetween(T value, T start, T end) {
return value.compareTo(start) >= 0 && value.compareTo(end) <= 0;
}
If you already use Apache commons lang, one option is to use the Range class instead of writing your own utility method:
@Test
public void bigDecimalInRange() {
Range<BigDecimal> myRange = Range.between(BigDecimal.TEN, BigDecimal.valueOf(300));
BigDecimal tooSmallAmount = new BigDecimal("2.50");
assertFalse(myRange.contains(tooSmallAmount));
BigDecimal rightAmount = new BigDecimal("10.01");
assertTrue(myRange.contains(rightAmount));
}
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