Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if BigDecimal value is in range

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.

like image 678
user3127896 Avatar asked Nov 18 '14 14:11

user3127896


People also ask

What is the range of BigDecimal?

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).

How do I know if my value is BigDecimal?

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.

How do you compare two big decimal values?

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.

How do I check if BigDecimal is null?

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.


2 Answers

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;
}
like image 191
Kirill Karandin Avatar answered Sep 20 '22 05:09

Kirill Karandin


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));
}
like image 22
beat Avatar answered Sep 21 '22 05:09

beat