Skip to main content
The ~/= operator is the compound assignment operator for truncating division. It divides the variable on the left-hand side by the operand on the right-hand side, discards any fractional component of the quotient (truncates towards zero), and assigns the resulting int back to the left-hand variable.

Syntax

variable ~/= divisor;

Operational Equivalence

The expression a ~/= b is semantically equivalent to:
a = a ~/ b;

Technical Behavior

  1. Integer Result: The operation always produces an int. It floors positive results and ceils negative results (rounds towards zero).
  2. Type Constraints:
    • Right-hand side (Divisor): Can be of type int or double.
    • Left-hand side (Variable): Must be a type compatible with an int assignment (e.g., int, num, or dynamic).
    • Incompatibility: Because the result is strictly an int, this operator cannot be used on variables explicitly typed as double. Dart does not perform implicit casting from int to double during variable assignment.

Examples

void main() {
  // Standard integer truncation
  int a = 10;
  a ~/= 3; // 10 / 3 is 3.33... -> Truncates to 3
  print(a); // Output: 3

  // Truncation with double operands
  // The variable must be 'num' or 'dynamic' to handle the type change 
  // from double (initial) to int (result).
  num b = 12.9; 
  b ~/= 3; // 12.9 / 3 is 4.3 -> Truncates to 4
  print(b); // Output: 4 (Type is now int)

  // Negative truncation (rounds toward zero)
  int c = -10;
  c ~/= 3; // -10 / 3 is -3.33... -> Truncates to -3
  print(c); // Output: -3
}
Master Dart with Deep Grasping Methodology!Learn More