Numbers and Math
Int and Double Arithmetic
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');
}
a ← 7 (int)
1void main() {2 int a = 7;3 double b = 2.5;values this step7 (int)ab ← 2.5 (double)
2int a = 7;3double b = 2.5;4var sum = a + b;values this step2.5 (double)bsum ← 9.5 (double)
3double b = 2.5;4var sum = a + b;5var asInt = b.toInt();values this step9.5 (double)sum7a2.5basInt ← 2 (int)
4var sum = a + b;5var asInt = b.toInt();6var asDouble = a.toDouble();values this step2 (int)asInt2.5basDouble ← 7.0 (double)
5var asInt = b.toInt();6var asDouble = a.toDouble();7var quotient = a / 2;values this step7.0 (double)asDouble7aquotient ← 3.5 (double)
6var asDouble = a.toDouble();7var quotient = a / 2;8print('$sum $asInt $asDouble $quotient');values this step3.5 (double)quotient7aprint('$sum $asInt $asDouble $quotient');
7 var quotient = a / 2;8 print('$sum $asInt $asDouble $quotient');9}output9.5 2 7.0 3.5values this step9.5sum2asInt7.0asDouble3.5quotient
Follow the Values
astarts as7, anint.bstarts as2.5, adouble.sumbecomes9.5.asIntis2,asDoubleis7.0, andquotientis3.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.