Division in Apex has a surprise for beginners: when both numbers are Integers, the result is also an Integer. The decimal part is cut off, not rounded.
Integer result = 7 / 2; System.debug(result); // 3, not 3.5
If you need the fraction, make at least one side of the division a Decimal. You can use a Decimal literal or cast one of the values:
Decimal exact = 7.0 / 2; // 3.5 Decimal alsoExact = (Decimal) 7 / 2; // 3.5
Many languages use the % operator to get the remainder of a division. Apex does not have a % operator. Instead, you call the Math.mod method:
Integer remainder = Math.mod(10, 3); // 1, because 10 = 3 * 3 + 1 Integer evenSplit = Math.mod(20, 5); // 0, because 20 divides evenly by 5
The remainder is handy in many everyday coding tasks:
Whenever a problem repeats in cycles, think of Math.mod.