Lesson 3 · 3 of 20
Numbers and arithmetic · Dart
Do arithmetic in Dart: +, -, *, division with / that gives a double, integer division ~/ and remainder %, rounding, and the += and ++ operators.

`${...}` puts the result of any expression inside a string, not just a variable: '34 + 10 = ${eggs + 10}' works out the sum and prints 44. The basic operators are the usual ones: +, - and *.
Division with `/` always gives a double, even when you divide two integers: 34 / 6 is 5.666666666666667. When what you want is how many times one number fits into another, use integer division `~/`, which keeps the whole part, and the remainder `%`: 34 eggs in boxes of 6 make 5 full boxes with 4 left over.
The same ~/ and % pair is useful everywhere: 135 ~/ 60 is 2 hours and 135 % 60 is 15 minutes. As in maths, * goes before +, and brackets change the order, which is why 2 + 3 * 4 gives 14 and (2 + 3) * 4 gives 20.
A double has methods for rounding: `toStringAsFixed(2)` gives the text with two decimals (the norm for money), round() rounds to the nearest whole number, floor() rounds down and ceil() rounds up.
To change a variable based on its own value, score += 5 means score = score + 5, and `score++` adds one. There are also -=, *= and --.
Code · main.dart
void main() { int eggs = 34; int perBox = 6; // ${...} puts the result of an expression in the text. print('34 + 10 = ${eggs + 10}'); print('34 * 2 = ${eggs * 2}'); // / always gives a double, even with two ints. print('34 / 6 = ${eggs / perBox}'); // ~/ keeps only the whole part; % gives the remainder. int boxes = eggs ~/ perBox; int left = eggs % perBox; print('$boxes full boxes and $left eggs left over'); // The same idea turns minutes into hours and minutes. int minutes = 135; print('$minutes min = ${minutes ~/ 60} h ${minutes % 60} min'); // * goes before +; brackets change the order. print('2 + 3 * 4 = ${2 + 3 * 4}, (2 + 3) * 4 = ${(2 + 3) * 4}'); // Doubles and their rounding methods. double total = 3.75 * 3; print('Total: $total = ${total.toStringAsFixed(2)} euros'); print('round: ${total.round()}, floor: ${total.floor()}, ceil: ${total.ceil()}'); // += and ++ update a variable. int score = 10; score += 5; score++; print('Score: $score');}Output · dart run main.dart
34 + 10 = 44 34 * 2 = 68 34 / 6 = 5.666666666666667 5 full boxes and 4 eggs left over 135 min = 2 h 15 min 2 + 3 * 4 = 14, (2 + 3) * 4 = 20 Total: 11.25 = 11.25 euros round: 11, floor: 11, ceil: 12 Score: 16
Key points
/always gives adouble.~/gives the whole part of a division;%the remainder.${expression}puts a calculation in the text.toStringAsFixed(2)prints two decimals.+=and++update a variable.
Exercise
Work out how many full weeks and spare days there are in 100 days with ~/ and %, and print the result in a sentence.