Skip to main content
The ~/ operator performs truncating division. It divides two numeric operands (dividend and divisor) and returns the integer quotient, discarding any fractional remainder.

Syntax

int result = dividend ~/ divisor;

Operational Semantics

  1. Return Type: The operator always returns an int.
  2. Rounding Behavior: The result is truncated towards zero. This is equivalent to calculating the standard division result and casting it to an integer ((a / b).toInt()).
    • Positive results are rounded down (e.g., 3.9 becomes 3).
    • Negative results are rounded up (e.g., -3.9 becomes -3).
  3. Exception Handling:
    • Integer Operands: If both operands are integers and the divisor is 0, the operation throws an IntegerDivisionByZeroException.
    • Double Operands: If any operand is a double and the result is not a finite number (e.g., dividing by zero resulting in Infinity, or 0.0 ~/ 0.0 resulting in NaN), the operation throws an UnsupportedError. This occurs because Infinity and NaN cannot be represented as an int.

Examples

The following code demonstrates the behavior of the ~/ operator with integers, doubles, and negative numbers.
void main() {
  // Standard integer division
  int a = 10 ~/ 3;      // Result: 3 (3.333... truncated)

  // Division with doubles
  int b = 10.5 ~/ 2.5;  // Result: 4 (4.2 truncated)

  // Truncation towards zero (Negative operands)
  int c = -10 ~/ 3;     // Result: -3 (Result is -3.33..., truncated to -3)
  
  // Comparison with floor()
  // -10 / 3 = -3.33...
  // floor() rounds to -4 (towards negative infinity)
  // ~/ rounds to -3 (towards zero)
}
Master Dart with Deep Grasping Methodology!Learn More