๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart Numbers

A Dart number is a value stored as an int or a double. An int is a whole number and a double carries a decimal part.

Division gives a double

The slash divides two whole numbers. Both answers print as doubles, and 2.0 keeps its decimal point.

void main() {
  print(7 / 2);
  print(10 / 5);
}

Truncating division drops the rest

The ~/ pair divides and drops the decimal part. A negative answer moves toward zero.

void main() {
  print(7 ~/ 2);
  print(-7 ~/ 2);
}

The remainder after division

The % sign gives the remainder after division. The remainder stays positive in Dart, even for -7 % 2.

void main() {
  print(7 % 2);
  print(-7 % 2);
}

Updating a number in place

Each compound assignment changes total and stores the new value. The three prints show total growing, shrinking, and doubling.

void main() {
  var total = 10;
  total += 5;
  print(total);
  total -= 3;
  print(total);
  total *= 2;
  print(total);
}

Whole and decimal values side by side

count holds a whole number and total holds a decimal number. Adding a whole number keeps an int, and adding a decimal keeps a double.

void main() {
  int count = 3;
  double total = 3.0;
  print(count);
  print(total);
  print(count + 1);
  print(total + 1.5);
}

Example

void main() {
  var price = 7;
  print(price / 2);
  print(price ~/ 2);
  print(price % 2);
  price += 1;
  print(price);
}

Key points

  • Use + to add, - to subtract, and * to multiply.
  • Division with / always gives a double, even when the answer is a whole number.
  • Truncating division with ~/ drops the decimal part of the answer.
  • Remainder with % gives the part left over after division.
  • Compound assignment with +=, -=, or *= stores the updated value back in the same variable.
  • A double prints with its decimal point, even when the part after the point is zero.
  • Adding a whole number to an int keeps an int, and adding a decimal to a double keeps a double.

In this example, price starts at 7. Dividing by 2 gives the double 3.5. Truncating division gives 3, and the remainder is 1. Adding 1 with += stores 8 in price.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does 7 ~/ 2 print?