Processing: Modulo with negative number

Created on 29 Mar 2020  路  1Comment  路  Source: processing/processing

Modulo is not working with value1 as a negative number.
println(-1 % 10);
The result of this was -1.
The expected result was 9.

Most helpful comment

No, this is as expected.

% is performed by the underlying Java operator. In Java, % is calculated as the remainder, and "the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive."

See the language spec:

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3

If you want the other behavior, try using Math.floorMod(int x, int y)
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int-

Further discussion though should be on the discourse.processing.org forums; issues is for bug reports only.

>All comments

No, this is as expected.

% is performed by the underlying Java operator. In Java, % is calculated as the remainder, and "the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive."

See the language spec:

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.3

If you want the other behavior, try using Math.floorMod(int x, int y)
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int-

Further discussion though should be on the discourse.processing.org forums; issues is for bug reports only.

Was this page helpful?
0 / 5 - 0 ratings