Check if BigDecimal value is in range

I have a BiGDecimal price , and I need to check if it is in a certain range. For example, there must 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 the BigDecimal type.

+7
java bigdecimal
source share
7 answers

This can be implemented using the method . compareTo () . For example:

 if ( price.compareTo( BigDecimal.valueOf( 500 ) > 0 && price.compareTo( BigDecimal.valueOf( 1000 ) < 0 ) { // price is larger than 500 and less than 1000 ... } 

Quote (and paraphrase) from JavaDoc:

The suggested idiom for making these comparisons is (x.compareTo (y) op 0), where op is one of six comparison operators [(<, ==,>,> = ,! =, <=)]

Greetings

+12
source share

There is no workaround in this. In the end, you can wrap it in a beautiful design template, but BigDecimal has only one method to compare.

My idea is to extract a method for the range:

 boolean isBetween(BigDecimal price, BigDecimal start, BigDecimal end){ return price.compareTo(start) > 0 && price.compareTo(end) < 0; } 
+6
source share

Allows you to make it general:

 public static <T extends Comparable<T>> boolean isBetween(T value, T start, T end) { return value.compareTo(start) >= 0 && value.compareTo(end) <= 0; } 
+4
source share

Use BigDecimal.compareTo(val) to compare if your number is greater, less, or equal.

returns -1, 0, or 1, because this BigDecimal is numerically smaller, equal, or greater than val.

 if (price.compareTo(BigDecimal.ZERO) >= 0 && price.compareTo(new BigDecimal(500)) <= 0) { .... } else if (price.compareTo(new BigDecimal(500)) >= 0 && price.compareTo(new BigDecimal(1000)) <= 0) { .... } else if (price.compareTo(price.compareTo(new BigDecimal(1000)) < 0) { .... } 
+1
source share

use compareTo method

java.math.BigDecimal.compareTo (BigDecimal val)

This method returns -1 if BigDecimal is less than val, 1 if BigDecimal is greater than val and 0 if BigDecimal is val

+1
source share

You can do sthg as follows:

 public class BigDecimalDemo { public static void main(String[] args) { // create 2 BigDecimal objects BigDecimal bg1, bg2; bg1 = new BigDecimal("10"); bg2 = new BigDecimal("20"); //create int object int res; res = bg1.compareTo(bg2); // compare bg1 with bg2 String str1 = "Both values are equal "; String str2 = "First Value is greater "; String str3 = "Second value is greater"; if( res == 0 ) System.out.println( str1 ); else if( res == 1 ) System.out.println( str2 ); else if( res == -1 ) System.out.println( str3 ); } } 

resource: http://www.tutorialspoint.com/java/math/bigdecimal_compareto.htm

+1
source share

Use the signum method from the BigDecimal class:

 private static boolean isBetween(BigDecimal amount, BigDecimal init, BigDecimal end) { return amount.subtract(init).signum() >= 0 && amount.subtract(end).signum() <= 0; } 
0
source share

All Articles