Math.floorMod()
A remainder that always has the sign of the divisor.
Available since: Java 8
Syntax
static int floorMod(int x, int y)Parameters
| Parameter | Type | Description |
|---|---|---|
| x | int / long | The dividend. |
| y | int / long | The divisor. |
Return value
int / longFor a positive y, a number from 0 to y - 1.
Examples
Compared with the % operator:
void main() {
IO.println(-1 % 7);
IO.println(Math.floorMod(-1, 7));
}Output:
-1
6A weekday "in a circle": 3 days before Monday (index 0):
void main() {
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
int index = Math.floorMod(0 - 3, 7);
IO.println(days[index]);
}Output:
FriNotes
For positive numbers floorMod() and % give the same result. They differ only for a negative dividend — exactly where % gives an awkward negative array index. Its partner Math.floorDiv() divides rounding down.
See also
- % — Returns the remainder of a division.
- Math.floor() — Rounds down to the nearest integer that is less than or equal.
Related recipes
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.