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!
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.
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.
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).
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.
if( x.remainder(new BigDecimal(20)).compareTo(BigDecimal.ZERO) == 0 ) {
// x is a multiple of 20
}
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");
}
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