Integer division written as a division followed by toInt

ID

dart.performance.use_truncating_division

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Idiom

Language

Dart

Description

Reports (a / b).toInt() and (a / b).truncate(), where the truncating division operator a ~/ b produces the same result in one step.

Rationale

/ always returns a double, so this form allocates and rounds a floating-point quotient and then throws the fraction away. Beyond the wasted work, the intermediate double loses precision once the operands exceed 2^53, so large integer divisions silently return a neighbouring value, and on the web compilers the quotient can be an infinity or NaN that toInt() then rejects at runtime. ~/ divides in the integer domain and never produces those intermediates.

The following code illustrates the pattern detected by this rule:

class Pager {
  // FLAGGED: Integer division written as a division followed by toInt
  int pages(int items, int perPage) => (items / perPage).toInt();
}

Remediation

Replace (a / b).toInt() and (a / b).truncate() with a ~/ b. When rounding matters, keep the explicit form and say which one is wanted - .ceil() and .round() are not the same operation, and .floor() differs from ~/ for a negative quotient because it rounds away from zero.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved