On this page26 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. Two Kinds of Numbers
- 2. int — Whole Numbers
- 3. double — Decimal Numbers
- 4. Exponent Notation
- 5. num — Either Kind
- 6. Readable Large Numbers with _
- 7. Hexadecimal Numbers
- 8. Asking a Number Questions
- 9. abs() — Distance from Zero
- 10. Rounding: round(), floor(), ceil(), truncate()
- 11. toStringAsFixed() — Formatting for Display
- 12. clamp() — Keeping a Number Inside Limits
- 13. Why 0.1 + 0.2 Is Not 0.3
- 14. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 09 — Numbers
| Category | 2 — Variables & Data Types |
| Lecture | 009 of 140 |
| Estimated video length | 9 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
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, not299.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 finalandconst- the core types
int,double,String, andbool - string interpolation with
$nameand${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:
void main() {
var price = 99.99;
var quantity = 3;
var total = price * quantity;
print('Total: $total');
}Total: 299.96999999999997Nobody 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, andnum - Write number literals, including negatives, exponents, and hexadecimal
- Use digit separators to make large numbers readable
- Ask a number questions with
isEven,isOdd,isNegative, andsign - Use
abs(),round(),floor(),ceil(),truncate(), andclamp() - Format a number for display with
toStringAsFixed() - Recognize why
0.1 + 0.2is not exactly0.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 isdouble.
void main() {
int pens = 3;
double rice = 1.25;
print(pens);
print(rice);
}3
1.252. int — Whole Numbers
An int holds whole numbers: positive, negative, or zero. Use it for things you count —
students, items, years, scores.
void main() {
int students = 32;
int temperature = -5;
int goals = 0;
print('$students, $temperature, $goals');
}32, -5, 0On 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:
void main() {
double price = 499.99;
double height = 5.8;
double balance = 1000;
print(price);
print(height);
print(balance);
}499.99
5.8
1000.04. 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:
void main() {
var distance = 1.5e3;
var tiny = 2.5e-3;
print(distance);
print(tiny);
}1500.0
0.0025A 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:
void main() {
num score = 90;
print(score);
score = 92.5;
print(score);
}90
92.5An 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:
void main() {
num points = 5;
int total = points;
print(total);
}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:
void main() {
var population = 10_000_000;
var price = 1_499.99;
print(population);
print(price);
}10000000
1499.99These 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:
void main() {
var red = 0xFF;
var white = 0xFFFFFF;
print(red);
print(white);
}255
167772150xFF 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:
void main() {
var marks = 78;
var balance = -250;
print(marks.isEven);
print(marks.isOdd);
print(balance.isNegative);
print(balance.sign);
}true
false
true
-1sign 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.
void main() {
var change = -15;
var temperature = -3.5;
print(change.abs());
print(temperature.abs());
}15
3.5Use 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:
void main() {
var price = 7.6;
print(price.round());
print(price.floor());
print(price.ceil());
print(price.truncate());
}8
7
8
7round()— to the nearest whole number (.5goes up, away from zero)floor()— always downceil()— always uptruncate()— chops off the decimal part
They differ for negatives. "Down" means towards the smaller number:
void main() {
var loss = -7.6;
print(loss.floor());
print(loss.truncate());
}-8
-7All 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:
void main() {
var total = 299.96999999999997;
var price = 50;
print(total.toStringAsFixed(2));
print(price.toStringAsFixed(2));
print(3.14159.toStringAsFixed(3));
}299.97
50.00
3.142The 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:
void main() {
var volume = 130;
var marks = -4;
print(volume.clamp(0, 100));
print(marks.clamp(0, 100));
print(75.clamp(0, 100));
}100
0
7513. 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:
void main() {
var sum = 0.1 + 0.2;
print(sum);
print(sum.toStringAsFixed(2));
}0.30000000000000004
0.30This 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
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)}');
}Total: 916.66
Rounded: 917
Over budget: false
Difference: 83.34pricePerKg 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
void main() {
int age = 21;
double height = 5.9;
print(age);
print(height);
}21
5.9Example 2 — A num Variable
void main() {
num weight = 60;
print(weight);
weight = 60.5;
print(weight);
}60
60.5Example 3 — Number Literals
void main() {
var million = 1_000_000;
var lightYearKm = 9.46e12;
var blue = 0x0000FF;
print(million);
print(lightYearKm);
print(blue);
}1000000
9460000000000.0
255Example 4 — Number Properties
void main() {
var number = 15;
print(number.isEven);
print(number.isOdd);
print(number.isNegative);
print(number.sign);
}false
true
false
1Example 5 — The Four Rounding Methods
void main() {
var value = 4.5;
print(value.round());
print(value.floor());
print(value.ceil());
print(value.truncate());
}5
4
5
4Example 6 — abs() and clamp()
void main() {
var difference = -42;
print(difference.abs());
print(difference.clamp(-10, 10));
}42
-10How it works
abs()removes the minus sign:42.clamp(-10, 10)keeps the value between-10and10;-42is below, so it becomes-10.
Example 7 — Student Marks
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()}');
}Student: Ali
Average: 85.7
Rounded average: 86How it works
- Division with
/always gives adouble, soaverageis85.66666666666667. toStringAsFixed(1)shows one decimal place:85.7.round()gives the nearest whole number as anint:86.
Example 8 — Shopping Total
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)}');
}Product: Notebook
Raw total: 449.84999999999997
Total: 449.85How it works
149.95 * 3should be449.85, but thedoubleresult carries a tiny error.toStringAsFixed(2)rounds it to two decimals for display.- Always format money before showing it to a customer.
Example 9 — Bank Balance
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)}');
}Owner: Sara
Overdrawn: true
Amount owed: 620.50How it works
- Digit separators make
2_500.0and3_120.5easy to read. - After the withdrawal,
balanceis-620.5, soisNegativeistrue. abs()drops the sign, andtoStringAsFixed(2)adds the second decimal:620.50.
Example 10 — Temperature Conversion
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()}');
}Celsius: 36.6
Fahrenheit: 97.9
Nearest degree: 98How it works
36.6 * 9 / 5 + 32is97.88000000000001— another tinydoubleerror.toStringAsFixed(1)shows97.9.round()gives98.
Common Beginner Mistakes
1. Putting a decimal into an int
void main() {
// int count = 2.5; // ✗
}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
void main() {
// int salary = 50,000; // ✗
}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
void main() {
// var price = 1000_; // ✗
}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
void main() {
print(-7.abs());
print((-7).abs());
}-7
7No 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
void main() {
// double price = 3.14159.toStringAsFixed(2); // ✗
}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
void main() {
var price = 9.99;
// price = price.round(); // ✗
}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
void main() {
num points = 5;
// int total = points; // ✗
}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
intfor things you count anddoublefor things you measure. - Use
numonly 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(), andtruncate()return anint. - 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:
Player: Zayan
Total: 126.75
Rounded: 127
Even: falseTry it yourself before opening the solution.
Show solution
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}');
}Player: Zayan
Total: 126.75
Rounded: 127
Even: falseHow it works
totalis adoublebecause two of the scores have decimals.round()turns126.75into theint127.isEvenworks on theintresult;127is odd, so it printsfalse.
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
- Store
pages = 320as anintandweight = 0.75as adouble, then print both, each on its own line. - Store the number one hundred million using digit separators and print it.
- Store
number = 24and print whether it is even, odd, and negative, each on its own line.
Application
-
Store
temperature = -12.4and print its absolute value. -
Store
value = 8.5and print the results ofround(),floor(),ceil(), andtruncate(), each on its own line. -
Store
price = 1250and print it asPrice: 1250.00. -
A game's health must stay between
0and100. Storehealth = 135and print the clamped value. -
This program does not compile. Fix it by changing one word, so that it prints
75and then75.5:void main() { int score = 75; print(score); score = 75.5; print(score); }
Challenge
- Sara buys
3shirts at799.99each. PrintTotal: 2399.97andRounded up: 2400. - Ali's account holds
1_200.0. He pays a bill of1_450.75. Print whether the account is overdrawn, and the amount owed with two decimals:Overdrawn: trueandOwed: 250.75.
Practice Answers
Question 1 — Solution
void main() {
int pages = 320;
double weight = 0.75;
print(pages);
print(weight);
}320
0.75Question 2 — Solution
void main() {
var hundredMillion = 100_000_000;
print(hundredMillion);
}100000000The underscores are only for reading; Dart prints the number without them.
Question 3 — Solution
void main() {
var number = 24;
print(number.isEven);
print(number.isOdd);
print(number.isNegative);
}true
false
falseQuestion 4 — Solution
void main() {
var temperature = -12.4;
print(temperature.abs());
}12.4Question 5 — Solution
void main() {
var value = 8.5;
print(value.round());
print(value.floor());
print(value.ceil());
print(value.truncate());
}9
8
9
8round() sends .5 up, so 8.5 becomes 9.
Question 6 — Solution
void main() {
var price = 1250;
print('Price: ${price.toStringAsFixed(2)}');
}Price: 1250.00toStringAsFixed() works on an int too, and adds the zeros.
Question 7 — Solution
void main() {
var health = 135;
print(health.clamp(0, 100));
}100Question 8 — Solution
Change int to num, so the variable accepts both kinds of number:
void main() {
num score = 75;
print(score);
score = 75.5;
print(score);
}75
75.5Changing int to double also compiles, but it prints 75.0 on the first line — num
keeps 75 as a whole number.
Question 9 — Solution
void main() {
var price = 799.99;
var quantity = 3;
var total = price * quantity;
print('Total: ${total.toStringAsFixed(2)}');
print('Rounded up: ${total.ceil()}');
}Total: 2399.97
Rounded up: 2400ceil() always rounds up, so 2399.97 becomes 2400.
Question 10 — Solution
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)}');
}Overdrawn: true
Owed: 250.75After the bill, balance is -250.75. isNegative reports the overdraft, and abs()
turns the debt into a positive amount for display.
Quick Revision
- What is the difference between an
intand adouble? - Which values can a
numvariable hold? - What does
1.5e3mean, and which type is it? - What are digit separators, and where may they appear?
- What does
signreturn for a negative number? - What is the difference between
floor()andtruncate()for-7.6? - Which type does
toStringAsFixed()return? - Why does
0.1 + 0.2print0.30000000000000004?
Key Takeaways
- Dart has two number types:
intfor whole numbers anddoublefor decimals. numaccepts both, but cannot be put directly into anintordoublevariable.- Literals can use exponents (
1.5e3, always adouble) and hexadecimal (0xFF). - Digit separators (
1_000_000) make numbers readable; commas are not allowed. - Properties like
isEven,isOdd,isNegative, andsignanswer questions about a number. abs(),clamp(), and the rounding methodsround(),floor(),ceil(), andtruncate()change a number; the rounding methods return anint.toStringAsFixed(n)returns aStringfor display — format at the end.- A
doublecannot 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'.