I needed to check if a BigDecimal instance is a multiple of another BigDecimal instance. Since I am restricted to Java 1.4, I couldn't make use of BigDecimal.remainder(...)
.
I came up with the following code:
/**
* Returns <code>true</code> if <code>multiple</code> is a multiple of <code>base</code>.
*
* @param multiple
* @param base
* @return
*/
public static boolean isMultipleOf(final BigDecimal multiple, final BigDecimal base)
{
if (multiple.compareTo(base) == 0)
return true;
try
{
multiple.divide(base, 0, BigDecimal.ROUND_UNNECESSARY);
return true;
}
catch(ArithmeticException e)
{
return false;
}
}
The code assumes that rounding is unnecessary only if the quotient of multiple
divided by base
is an integer. Is this assumption correct?
Edit
Incorporated the hint by Lando to explicitly set the scale of the quotient to 0
. Otherwise the following call would have wrongly returned true
:
isMultipleOf(new BigDecimal("10.25"), new BigDecimal("5"));
Edit
Wrote a JUnit test and found out I have to take care of the special case where both multiple
and base
are 0
. So I added a test for equality to the code above.
The javadoc says...
Throws: ArithmeticException - if divisor==0, or roundingMode==ROUND_UNNECESSARY and this.scale() is insufficient to represent the result of the division exactly.
So the assumption seems correct that an ArithmeticException
will occur if the scale()
is not sufficient; i.e. remainder is non-zero.