Watch the video (9 min)
On this page26 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. Two Kinds of Numbers
  5. 2. int — Whole Numbers
  6. 3. double — Decimal Numbers
  7. 4. Exponent Notation
  8. 5. num — Either Kind
  9. 6. Readable Large Numbers with _
  10. 7. Hexadecimal Numbers
  11. 8. Asking a Number Questions
  12. 9. abs() — Distance from Zero
  13. 10. Rounding: round(), floor(), ceil(), truncate()
  14. 11. toStringAsFixed() — Formatting for Display
  15. 12. clamp() — Keeping a Number Inside Limits
  16. 13. Why 0.1 + 0.2 Is Not 0.3
  17. 14. A Real-World Example
  18. Code Examples
  19. Common Beginner Mistakes
  20. Best Practices
  21. Mini Challenge
  22. Practice Questions
  23. Practice Answers
  24. Quick Revision
  25. Key Takeaways
  26. What's Next?

Lecture 09 — Numbers

Category2 — Variables & Data Types
Lecture009 of 140
Estimated video length9 min
TargetDart 3.12.2
LevelBeginner

So far a number was just something to store and print. Dart numbers can also answer questions about themselves — is it even? is it negative? — and round and format themselves, so a price prints as 299.97, not 299.96999999999997.

Contents

Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways

Every error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2, so you will recognize it when you meet it yourself.


Prerequisites

Students should already understand, from Lectures 001–008:

  • declaring variables with a type or with var
  • final and const
  • the core types int, double, String, and bool
  • string interpolation with $name and ${expression}
  • calling a method on a value with a dot, such as name.toUpperCase()

Connection With Previous Lectures

In Lecture 008, a String came with tools: toUpperCase(), length, contains(). Numbers have been plainer so far. Look at this bill:

dart
void main() {
  var price = 99.99;
  var quantity = 3;
  var total = price * quantity;
  print('Total: $total');
}
output
Total: 299.96999999999997

Nobody wants to pay 299.96999999999997. We need the total shown as 299.97, and we may want to round it, check whether it is negative, or keep it inside a limit. Numbers have their own tools for all of this.


Learning Objectives

By the end of this lecture you will be able to:

  • Explain the difference between int, double, and num
  • Write number literals, including negatives, exponents, and hexadecimal
  • Use digit separators to make large numbers readable
  • Ask a number questions with isEven, isOdd, isNegative, and sign
  • Use abs(), round(), floor(), ceil(), truncate(), and clamp()
  • Format a number for display with toStringAsFixed()
  • Recognize why 0.1 + 0.2 is not exactly 0.3
  • Recognize the error messages Dart produces for common number mistakes

1. Two Kinds of Numbers

Dart has two number types. An int is a whole number. A double is a number with a decimal point.

Analogy — think of a shop counter. Some things are counted in whole pieces: 3 pens, 12 eggs. Others are measured on a scale: 1.25 kg of rice. Counting is int; measuring is double.

dart
void main() {
  int pens = 3;
  double rice = 1.25;
  print(pens);
  print(rice);
}
output
3
1.25

2. int — Whole Numbers

An int holds whole numbers: positive, negative, or zero. Use it for things you count — students, items, years, scores.

dart
void main() {
  int students = 32;
  int temperature = -5;
  int goals = 0;
  print('$students, $temperature, $goals');
}
output
32, -5, 0

On your computer, an int can hold numbers up to about nine quintillion (9223372036854775807) — far bigger than anything in this course.


3. double — Decimal Numbers

A double holds numbers with a fractional part: prices, weights, temperatures. As you saw in Lecture 004, a whole number stored in a double still prints with .0:

dart
void main() {
  double price = 499.99;
  double height = 5.8;
  double balance = 1000;
  print(price);
  print(height);
  print(balance);
}
output
499.99
5.8
1000.0

4. Exponent Notation

Very large or very small decimals can be written with e, meaning "times ten to the power of". 1.5e3 is 1.5 × 1000:

dart
void main() {
  var distance = 1.5e3;
  var tiny = 2.5e-3;
  print(distance);
  print(tiny);
}
output
1500.0
0.0025

A number written with e is always a double, even when the result is whole — that is why 1500.0 has its .0.


5. num — Either Kind

num is the parent of both int and double. A num variable accepts either kind of number:

dart
void main() {
  num score = 90;
  print(score);
  score = 92.5;
  print(score);
}
output
90
92.5

An int variable could not take 92.5. A num can. The price is that Dart knows less about the value — so a num cannot be put into an int variable:

dart
void main() {
  num points = 5;
  int total = points;
  print(total);
}
output
Error: A value of type 'num' can't be assigned to a variable of type 'int'.
  int total = points;
              ^

Use num only when a value really can be either. Most of the time, choose int or double. Turning one number type into another is the topic of Lecture 010.


6. Readable Large Numbers with _

A long number is hard to read: is 10000000 ten million or one million? Dart lets you put underscores between digits. They are ignored by Dart and exist only for your eyes:

dart
void main() {
  var population = 10_000_000;
  var price = 1_499.99;
  print(population);
  print(price);
}
output
10000000
1499.99

These are called digit separators. An underscore must sit between two digits — not at the start or end. You cannot use commas: 1,000 is not a number in Dart.


7. Hexadecimal Numbers

Numbers can also be written in hexadecimal (base 16) by starting with 0x. The digits run 0–9 and then A–F. You will meet them mostly in colors:

dart
void main() {
  var red = 0xFF;
  var white = 0xFFFFFF;
  print(red);
  print(white);
}
output
255
16777215

0xFF is just another way to write 255 — it is still an int.


8. Asking a Number Questions

Every number has properties — values you read with a dot, no parentheses. Each one answers a question:

dart
void main() {
  var marks = 78;
  var balance = -250;
  print(marks.isEven);
  print(marks.isOdd);
  print(balance.isNegative);
  print(balance.sign);
}
output
true
false
true
-1

sign is -1 for negatives, 0 for zero, and 1 for positives. The true/false answers are bool values — very useful once we learn if in Lecture 022.


9. abs() — Distance from Zero

Methods are actions; they end with parentheses. abs() gives the absolute value: the number without its minus sign.

dart
void main() {
  var change = -15;
  var temperature = -3.5;
  print(change.abs());
  print(temperature.abs());
}
output
15
3.5

Use it when only the size matters — "the price changed by 15", whichever direction.


10. Rounding: round(), floor(), ceil(), truncate()

Four methods turn a double into a whole number, each in its own way:

dart
void main() {
  var price = 7.6;
  print(price.round());
  print(price.floor());
  print(price.ceil());
  print(price.truncate());
}
output
8
7
8
7
  • round() — to the nearest whole number (.5 goes up, away from zero)
  • floor() — always down
  • ceil() — always up
  • truncate() — chops off the decimal part

They differ for negatives. "Down" means towards the smaller number:

dart
void main() {
  var loss = -7.6;
  print(loss.floor());
  print(loss.truncate());
}
output
-8
-7

All four give back an int, not a double — notice there is no .0 in the output.


11. toStringAsFixed() — Formatting for Display

toStringAsFixed(n) shows a number with exactly n digits after the decimal point. It rounds when needed and pads with zeros when needed:

dart
void main() {
  var total = 299.96999999999997;
  var price = 50;
  print(total.toStringAsFixed(2));
  print(price.toStringAsFixed(2));
  print(3.14159.toStringAsFixed(3));
}
output
299.97
50.00
3.142

The result is a String — text ready to print, not a number to calculate with. Do your calculations first, and format at the very end.


12. clamp() — Keeping a Number Inside Limits

clamp(low, high) keeps a number between two limits. Anything below low becomes low; anything above high becomes high:

dart
void main() {
  var volume = 130;
  var marks = -4;
  print(volume.clamp(0, 100));
  print(marks.clamp(0, 100));
  print(75.clamp(0, 100));
}
output
100
0
75

13. Why 0.1 + 0.2 Is Not 0.3

A double stores decimals in binary, and some decimals — like 0.1 — cannot be stored exactly. The tiny error shows up in results:

dart
void main() {
  var sum = 0.1 + 0.2;
  print(sum);
  print(sum.toStringAsFixed(2));
}
output
0.30000000000000004
0.30

This is not a Dart bug; almost every language does it. It is the reason for the 299.96999999999997 at the start of this lecture, and why money is formatted with toStringAsFixed(2) before it is shown.


14. A Real-World Example

dart
void main() {
  const pricePerKg = 333.33;
  var weight = 2.75;
  var budget = 1_000;

  var total = pricePerKg * weight;
  var left = budget - total;

  print('Total: ${total.toStringAsFixed(2)}');
  print('Rounded: ${total.round()}');
  print('Over budget: ${left.isNegative}');
  print('Difference: ${left.abs().toStringAsFixed(2)}');
}
output
Total: 916.66
Rounded: 917
Over budget: false
Difference: 83.34

pricePerKg and weight are double, so total is a double. Each line asks the number something different: format it, round it, check its sign, and measure its size.


Code Examples

Example 1 — int and double

dart
void main() {
  int age = 21;
  double height = 5.9;
  print(age);
  print(height);
}
output
21
5.9

Example 2 — A num Variable

dart
void main() {
  num weight = 60;
  print(weight);
  weight = 60.5;
  print(weight);
}
output
60
60.5

Example 3 — Number Literals

dart
void main() {
  var million = 1_000_000;
  var lightYearKm = 9.46e12;
  var blue = 0x0000FF;
  print(million);
  print(lightYearKm);
  print(blue);
}
output
1000000
9460000000000.0
255

Example 4 — Number Properties

dart
void main() {
  var number = 15;
  print(number.isEven);
  print(number.isOdd);
  print(number.isNegative);
  print(number.sign);
}
output
false
true
false
1

Example 5 — The Four Rounding Methods

dart
void main() {
  var value = 4.5;
  print(value.round());
  print(value.floor());
  print(value.ceil());
  print(value.truncate());
}
output
5
4
5
4

Example 6 — abs() and clamp()

dart
void main() {
  var difference = -42;
  print(difference.abs());
  print(difference.clamp(-10, 10));
}
output
42
-10

How it works

  1. abs() removes the minus sign: 42.
  2. clamp(-10, 10) keeps the value between -10 and 10; -42 is below, so it becomes -10.

Example 7 — Student Marks

dart
void main() {
  var student = 'Ali';
  var math = 87;
  var science = 92;
  var english = 78;
  var average = (math + science + english) / 3;
  print('Student: $student');
  print('Average: ${average.toStringAsFixed(1)}');
  print('Rounded average: ${average.round()}');
}
output
Student: Ali
Average: 85.7
Rounded average: 86

How it works

  1. Division with / always gives a double, so average is 85.66666666666667.
  2. toStringAsFixed(1) shows one decimal place: 85.7.
  3. round() gives the nearest whole number as an int: 86.

Example 8 — Shopping Total

dart
void main() {
  var product = 'Notebook';
  var price = 149.95;
  var quantity = 3;
  var total = price * quantity;
  print('Product: $product');
  print('Raw total: $total');
  print('Total: ${total.toStringAsFixed(2)}');
}
output
Product: Notebook
Raw total: 449.84999999999997
Total: 449.85

How it works

  1. 149.95 * 3 should be 449.85, but the double result carries a tiny error.
  2. toStringAsFixed(2) rounds it to two decimals for display.
  3. Always format money before showing it to a customer.

Example 9 — Bank Balance

dart
void main() {
  var owner = 'Sara';
  var balance = 2_500.0;
  var withdrawal = 3_120.5;
  balance = balance - withdrawal;
  print('Owner: $owner');
  print('Overdrawn: ${balance.isNegative}');
  print('Amount owed: ${balance.abs().toStringAsFixed(2)}');
}
output
Owner: Sara
Overdrawn: true
Amount owed: 620.50

How it works

  1. Digit separators make 2_500.0 and 3_120.5 easy to read.
  2. After the withdrawal, balance is -620.5, so isNegative is true.
  3. abs() drops the sign, and toStringAsFixed(2) adds the second decimal: 620.50.

Example 10 — Temperature Conversion

dart
void main() {
  var celsius = 36.6;
  var fahrenheit = celsius * 9 / 5 + 32;
  print('Celsius: $celsius');
  print('Fahrenheit: ${fahrenheit.toStringAsFixed(1)}');
  print('Nearest degree: ${fahrenheit.round()}');
}
output
Celsius: 36.6
Fahrenheit: 97.9
Nearest degree: 98

How it works

  1. 36.6 * 9 / 5 + 32 is 97.88000000000001 — another tiny double error.
  2. toStringAsFixed(1) shows 97.9.
  3. round() gives 98.

Common Beginner Mistakes

1. Putting a decimal into an int

dart
void main() {
  // int count = 2.5; // ✗
}
output
Error: A value of type 'double' can't be assigned to a variable of type 'int'.

If a value can have a decimal part, use double.

2. Writing commas in a number

dart
void main() {
  // int salary = 50,000; // ✗
}
output
Error: Expected an identifier, but got '000'.

Dart reads the comma as a separator between two things. Use an underscore: 50_000.

3. Putting _ at the edge of a number

dart
void main() {
  // var price = 1000_; // ✗
}
output
Error: Digit separators ('_') in a number literal can only be placed between two digits.

The underscore must sit between digits: 1_000.

4. Calling a method on a negative literal without parentheses

dart
void main() {
  print(-7.abs());
  print((-7).abs());
}
output
-7
7

No error — just a wrong answer. Dart reads -7.abs() as -(7.abs()). Wrap a negative literal in parentheses, or store it in a variable first.

5. Storing toStringAsFixed() in a number variable

dart
void main() {
  // double price = 3.14159.toStringAsFixed(2); // ✗
}
output
Error: A value of type 'String' can't be assigned to a variable of type 'double'.

toStringAsFixed() returns text. Keep the number for calculations and format only when printing.

6. Assigning a rounded value back to a double variable

dart
void main() {
  var price = 9.99;
  // price = price.round(); // ✗
}
output
Error: A value of type 'int' can't be assigned to a variable of type 'double'.

round() returns an int, and price is a double. Store the result in a new variable: var rounded = price.round();.

7. Putting a num into an int

dart
void main() {
  num points = 5;
  // int total = points; // ✗
}
output
Error: A value of type 'num' can't be assigned to a variable of type 'int'.

Declare points as int if it is always whole.


Best Practices

  • Use int for things you count and double for things you measure.
  • Use num only when a value really can be either kind.
  • Write large numbers with digit separators: 1_000_000.
  • Calculate with numbers; format with toStringAsFixed() only at the end, for display.
  • Show money with exactly two decimals: toStringAsFixed(2).
  • Remember that round(), floor(), ceil(), and truncate() return an int.
  • Wrap negative literals in parentheses before calling a method: (-7).abs().

Mini Challenge

Zayan scored 47.5, 38.25, and 41 in three games. Calculate his total, then print it with two decimals, rounded to the nearest whole number, and whether the rounded score is even.

Your program should print exactly:

output
Player: Zayan
Total: 126.75
Rounded: 127
Even: false

Try it yourself before opening the solution.

Show solution
dart
void main() {
  var player = 'Zayan';
  var total = 47.5 + 38.25 + 41;
  var rounded = total.round();
  print('Player: $player');
  print('Total: ${total.toStringAsFixed(2)}');
  print('Rounded: $rounded');
  print('Even: ${rounded.isEven}');
}
output
Player: Zayan
Total: 126.75
Rounded: 127
Even: false

How it works

  1. total is a double because two of the scores have decimals.
  2. round() turns 126.75 into the int 127.
  3. isEven works on the int result; 127 is odd, so it prints false.

Practice Questions

Work through these in order — they run from beginner to application to challenge. Every question gives you exact values, so you can compare your output with the answers.

Beginner

  1. Store pages = 320 as an int and weight = 0.75 as a double, then print both, each on its own line.
  2. Store the number one hundred million using digit separators and print it.
  3. Store number = 24 and print whether it is even, odd, and negative, each on its own line.

Application

  1. Store temperature = -12.4 and print its absolute value.

  2. Store value = 8.5 and print the results of round(), floor(), ceil(), and truncate(), each on its own line.

  3. Store price = 1250 and print it as Price: 1250.00.

  4. A game's health must stay between 0 and 100. Store health = 135 and print the clamped value.

  5. This program does not compile. Fix it by changing one word, so that it prints 75 and then 75.5:

    dart
    void main() {
      int score = 75;
      print(score);
      score = 75.5;
      print(score);
    }

Challenge

  1. Sara buys 3 shirts at 799.99 each. Print Total: 2399.97 and Rounded up: 2400.
  2. Ali's account holds 1_200.0. He pays a bill of 1_450.75. Print whether the account is overdrawn, and the amount owed with two decimals: Overdrawn: true and Owed: 250.75.

Practice Answers

Question 1 — Solution

dart
void main() {
  int pages = 320;
  double weight = 0.75;
  print(pages);
  print(weight);
}
output
320
0.75

Question 2 — Solution

dart
void main() {
  var hundredMillion = 100_000_000;
  print(hundredMillion);
}
output
100000000

The underscores are only for reading; Dart prints the number without them.

Question 3 — Solution

dart
void main() {
  var number = 24;
  print(number.isEven);
  print(number.isOdd);
  print(number.isNegative);
}
output
true
false
false

Question 4 — Solution

dart
void main() {
  var temperature = -12.4;
  print(temperature.abs());
}
output
12.4

Question 5 — Solution

dart
void main() {
  var value = 8.5;
  print(value.round());
  print(value.floor());
  print(value.ceil());
  print(value.truncate());
}
output
9
8
9
8

round() sends .5 up, so 8.5 becomes 9.

Question 6 — Solution

dart
void main() {
  var price = 1250;
  print('Price: ${price.toStringAsFixed(2)}');
}
output
Price: 1250.00

toStringAsFixed() works on an int too, and adds the zeros.

Question 7 — Solution

dart
void main() {
  var health = 135;
  print(health.clamp(0, 100));
}
output
100

Question 8 — Solution

Change int to num, so the variable accepts both kinds of number:

dart
void main() {
  num score = 75;
  print(score);
  score = 75.5;
  print(score);
}
output
75
75.5

Changing int to double also compiles, but it prints 75.0 on the first line — num keeps 75 as a whole number.

Question 9 — Solution

dart
void main() {
  var price = 799.99;
  var quantity = 3;
  var total = price * quantity;
  print('Total: ${total.toStringAsFixed(2)}');
  print('Rounded up: ${total.ceil()}');
}
output
Total: 2399.97
Rounded up: 2400

ceil() always rounds up, so 2399.97 becomes 2400.

Question 10 — Solution

dart
void main() {
  var balance = 1_200.0;
  var bill = 1_450.75;
  balance = balance - bill;
  print('Overdrawn: ${balance.isNegative}');
  print('Owed: ${balance.abs().toStringAsFixed(2)}');
}
output
Overdrawn: true
Owed: 250.75

After the bill, balance is -250.75. isNegative reports the overdraft, and abs() turns the debt into a positive amount for display.


Quick Revision

  1. What is the difference between an int and a double?
  2. Which values can a num variable hold?
  3. What does 1.5e3 mean, and which type is it?
  4. What are digit separators, and where may they appear?
  5. What does sign return for a negative number?
  6. What is the difference between floor() and truncate() for -7.6?
  7. Which type does toStringAsFixed() return?
  8. Why does 0.1 + 0.2 print 0.30000000000000004?

Key Takeaways

  • Dart has two number types: int for whole numbers and double for decimals.
  • num accepts both, but cannot be put directly into an int or double variable.
  • Literals can use exponents (1.5e3, always a double) and hexadecimal (0xFF).
  • Digit separators (1_000_000) make numbers readable; commas are not allowed.
  • Properties like isEven, isOdd, isNegative, and sign answer questions about a number.
  • abs(), clamp(), and the rounding methods round(), floor(), ceil(), and truncate() change a number; the rounding methods return an int.
  • toStringAsFixed(n) returns a String for display — format at the end.
  • A double cannot store every decimal exactly, so always format money before showing it.

What's Next?

Lecture 10 — Type Checking & Conversion. In this lecture round() turned a double into an int, but a num refused to go into an int variable, and a formatted price became a String we could not calculate with. Next we will learn how to check a value's type while the program runs, and how to convert between numbers and text — including reading a number out of a string like '42'.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.