diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 71e65b990..723d3c955 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -29,6 +29,7 @@
+ Modulo (%) on BigInteger operands is inconsistent with other numeric types for negative operands.
Interpolation strings are parsed with the engine features instead of those of their script.
A jexl.options pragma modifies the engine options when evaluated with a plain context.
diff --git a/src/main/java/org/apache/commons/jexl3/JexlArithmetic.java b/src/main/java/org/apache/commons/jexl3/JexlArithmetic.java
index 18bff9cf8..8d2e03771 100644
--- a/src/main/java/org/apache/commons/jexl3/JexlArithmetic.java
+++ b/src/main/java/org/apache/commons/jexl3/JexlArithmetic.java
@@ -1387,7 +1387,7 @@ public Object mod(final Object left, final Object right) {
if (BigInteger.ZERO.equals(r)) {
throw new ArithmeticException("%");
}
- final BigInteger result = l.mod(r);
+ final BigInteger result = l.remainder(r);
return narrowBigInteger(left, right, result);
}
diff --git a/src/test/java/org/apache/commons/jexl3/ArithmeticTest.java b/src/test/java/org/apache/commons/jexl3/ArithmeticTest.java
index 8854bcb74..da06a0520 100644
--- a/src/test/java/org/apache/commons/jexl3/ArithmeticTest.java
+++ b/src/test/java/org/apache/commons/jexl3/ArithmeticTest.java
@@ -1853,6 +1853,27 @@ void testModEdge() {
assertNullOperand(() -> jexla.divide(null, null));
}
+ @Test
+ void testModBigIntegerNegative() {
+ // '%' on BigInteger operands must use the truncated remainder (the sign follows the
+ // dividend), consistent with the long, double and BigDecimal code paths and with Java's
+ // '%' operator. Previously the BigInteger branch used BigInteger.mod(), which returns a
+ // non-negative result and throws for a negative divisor, so '-39 % 2' depended on whether
+ // the operands were represented as long or BigInteger.
+ final long[][] cases = { { -39, 2 }, { 39, -2 }, { -39, -2 }, { 39, 2 }, { -7, 3 }, { 7, -3 } };
+ for (final long[] c : cases) {
+ final long x = c[0];
+ final long y = c[1];
+ final Number longResult = (Number) jexla.mod(x, y);
+ final Number bigResult = (Number) jexla.mod(BigInteger.valueOf(x), BigInteger.valueOf(y));
+ assertEquals(x % y, longResult.longValue());
+ assertEquals(x % y, bigResult.longValue(),
+ "BigInteger '%' should match the long/Java result for " + x + " % " + y);
+ }
+ // A negative divisor must not throw for BigInteger operands (the long path does not throw).
+ assertEquals(1L, ((Number) jexla.mod(BigInteger.valueOf(39), BigInteger.valueOf(-2))).longValue());
+ }
+
/**
* JEXL-156.
*/