Skip to main content
The % operator calculates the Euclidean modulo of two numeric operands. Unlike the remainder operator found in languages such as C or Java (which typically perform truncated division), Dart’s % operator guarantees a non-negative result for all finite inputs, regardless of the signs of the dividend or divisor.

Syntax

dividend % divisor

Return Type

The static type of the result is determined by the operand types:
  • int: Returned if both operands are of type int.
  • double: Returned if at least one operand is of type double.

Operational Logic

The operator adheres to the mathematical definition of Euclidean division. For an expression a % b, the result r satisfies the following invariant:
  1. 0 <= r < |b| (The result is non-negative and strictly less than the absolute value of the divisor).
  2. a = b * q + r for some integer q.
This behavior is distinct from the remainder() method, which performs truncated division where the result adopts the sign of the dividend.

Integer Behavior

The operator resolves to a non-negative integer even when the dividend is negative.
void main() {
  // Standard positive division
  // 5 = 3 * 1 + 2
  print(5 % 3);    // Output: 2

  // Negative dividend
  // -5 = 3 * (-2) + 1
  print(-5 % 3);   // Output: 1

  // Negative divisor
  // 5 = -3 * (-1) + 2
  print(5 % -3);   // Output: 2

  // Comparison with .remainder()
  // .remainder() preserves the sign of the dividend
  print((-5).remainder(3)); // Output: -2
}

Floating-Point Behavior

The operator supports floating-point operands, returning the floating-point remainder of the Euclidean division.
void main() {
  // 5.5 = 1.5 * 3 + 1.0
  print(5.5 % 1.5);  // Output: 1.0
  
  // -5.5 = 1.5 * (-4) + 0.5
  print(-5.5 % 1.5); // Output: 0.5
}

Edge Cases

  • Integer Division by Zero (VM): If both operands are integers and the divisor is 0, the Dart VM throws an IntegerDivisionByZeroException.
  • Integer Division by Zero (Web): When compiled to JavaScript, integers are represented as floating-point numbers. Consequently, division by zero results in NaN rather than throwing an exception.
  • Floating-Point Division by Zero: If any operand is a double and the divisor is 0 or 0.0, the result is NaN.
// Running on Dart VM
print(5 % 0);   // Unhandled Exception: IntegerDivisionByZeroException
print(5.0 % 0); // Output: NaN
Master Dart with Deep Grasping Methodology!Learn More