Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do BigDecimal modulus comparison

Im getting confused on how to write a simple modulus comparison if statement. I basically just want to check if x is a multiple of 20 when x is a BigDecimal. Thanks!

like image 938
user3571618 Avatar asked Apr 27 '14 22:04

user3571618


People also ask

How can I compare two BigDecimal values?

compareTo(BigDecimal val) compares the BigDecimal Object with the specified BigDecimal value. 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.

How does BigDecimal compare to 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.

How do you know if BigDecimal is positive or negative?

5. Using the signum Method. The BigDeicmal class provides the signum method to tell if the given BigDecimal object's value is negative (-1), zero (0), or positive (1).

What is rounding mode in BigDecimal Java?

Description. The java. math. BigDecimal. setScale(int newScale, RoundingMode roundingMode) returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.


2 Answers

if( x.remainder(new BigDecimal(20)).compareTo(BigDecimal.ZERO) == 0 ) {
   // x is a multiple of 20
}
like image 182
Dawood ibn Kareem Avatar answered Oct 16 '22 00:10

Dawood ibn Kareem


You should use remainder() method:

BigDecimal x = new BigDecimal(100);
BigDecimal remainder = x.remainder(new BigDecimal(20));
if (BigDecimal.ZERO.compareTo(remainder) == 0) {
    System.out.println("x can be divided by 20");
}
like image 34
Alexey Malev Avatar answered Oct 16 '22 01:10

Alexey Malev