Numbers
Prerequisites: Data types and type inference
Dart's number types are int (whole numbers) and double (decimals).
Both are subtypes of num.
Example
void main() {
print(7 + 2);
print(7 - 2);
print(7 * 2);
print(7 / 2);
print(7 ~/ 2);
print(7 % 2);
print(6 / 2);
print(10 / 3);
print(-7 ~/ 2);
}
Expected output
9
5
14
3.5
3
1
3.0
3.3333333333333335
-3
Line by line:
/always returns adoublein Dart, even for6 / 2.~/is integer division: it divides and drops the remainder, returning anint.-7 ~/ 2is-3— it rounds toward zero.%gives the remainder, handy for checking whether a number is even.- Doubles are approximate:
10 / 3shows the tiny rounding error built into how computers store decimals.
Useful number methods
import 'dart:math';
void main() {
print((-5).abs());
print(3.7.round());
print(3.7.floor());
print(3.2.ceil());
print(3.99.toInt());
print(3.14159.toStringAsFixed(2));
print(17.clamp(1, 10));
print(10.isEven);
print(max(3, 9));
print(pow(2, 10));
print(sqrt(16));
}
5
4
3
4
3
3.14
10
true
9
1024
4.0
toInt()truncates;round()rounds to the nearest whole number.toStringAsFixed(2)formats with two decimal places (it returns aString).max,pow, andsqrtcome fromdart:math, imported at the top.
Common mistakes
- Expecting
7 / 2to be3. Use~/for integer division. - Using
doublefor money.0.1 + 0.2is0.30000000000000004. Store cents asint, or use a decimal package.
Practice
A pizza has 8 slices shared by 3 people. Print how many whole slices each person gets, how many are left over, and the exact share with two decimal places.
Show solution
void main() {
const slices = 8;
const people = 3;
print(slices ~/ people);
print(slices % people);
print((slices / people).toStringAsFixed(2));
}
2
2
2.67