Dart has int for whole numbers and double for IEEE-754 fractional values. Mixing the two widens the result to a double. / always returns a double; use ~/ for integer division. toInt() truncates a double toward zero, and toDouble() widens an int.

Program

Play the program to widen int + double, convert values in both numeric directions, and watch / produce a double from two int operands.

int_double.dart
Replay: real traced execution (multi-file project)
void main() {
  int a = 7;
  double b = 2.5;
  var sum = a + b;
  var asInt = b.toInt();
  var asDouble = a.toDouble();
  var quotient = a / 2;
  print('$sum $asInt $asDouble $quotient');
}
  1. a ← 7 (int)

    1void main() {2  int a = 7;3  double b = 2.5;
    values this step7 (int)a
  2. b ← 2.5 (double)

    2int a = 7;3double b = 2.5;4var sum = a + b;
    values this step2.5 (double)b
  3. sum ← 9.5 (double)

    3double b = 2.5;4var sum = a + b;5var asInt = b.toInt();
    values this step9.5 (double)sum7a2.5b
  4. asInt ← 2 (int)

    4var sum = a + b;5var asInt = b.toInt();6var asDouble = a.toDouble();
    values this step2 (int)asInt2.5b
  5. asDouble ← 7.0 (double)

    5var asInt = b.toInt();6var asDouble = a.toDouble();7var quotient = a / 2;
    values this step7.0 (double)asDouble7a
  6. quotient ← 3.5 (double)

    6var asDouble = a.toDouble();7var quotient = a / 2;8print('$sum $asInt $asDouble $quotient');
    values this step3.5 (double)quotient7a
  7. print('$sum $asInt $asDouble $quotient');

    7  var quotient = a / 2;8  print('$sum $asInt $asDouble $quotient');9}
    output9.5 2 7.0 3.5
    values this step9.5sum2asInt7.0asDouble3.5quotient

Follow the Values

  1. a starts as 7, an int.
  2. b starts as 2.5, a double.
  3. sum becomes 9.5.
  4. asInt is 2, asDouble is 7.0, and quotient is 3.5.
  5. The program prints 9.5 2 7.0 3.5. | name | value | | --- | --- | | sum | 9.5 | | asInt | 2 | | asDouble | 7.0 | | quotient | 3.5 |
widening `int + double` evaluates to a `double`-valued result; the `int` is widened to match.
/ `/` returns a `double` even when both operands are `int`. Use `~/` for an integer quotient.
conversions `double.toInt()` truncates toward zero; `int.toDouble()` widens a whole number to a `double`.

Exercise: int_double.dart

Reproduce 9.5 2 7.0 3.5, then identify which value came from converting a double to an int.