Back to quest
Dart Basics & Data TypesLevel 6 / 32

Numbers: int and double

Working with integers and floating-point numbers

Numbers are fundamental to programming. Dart provides two main numeric types: int for whole numbers and double for decimal numbers. Understanding how to work with numbers effectively is essential for calculations, data processing, and building real-world applications.

Integer Type (int)

The int type represents whole numbers without decimal points. In Dart, integers can be as large as the platform allows - on native platforms, they can be 64-bit values ranging from -2⁶³ to 2⁶³-1.

Working with Integers

example.dart
1// Integer declarations
2int age = 25;
3int score = 100;
4int temperature = -5;
5 
6// Large integers
7int bigNumber = 9223372036854775807; // Maximum 64-bit int
8 
9// Integer arithmetic
10int a = 10;
11int b = 3;
12 
13print(a + b); // 13 - Addition
14print(a - b); // 7 - Subtraction
15print(a * b); // 30 - Multiplication
16print(a ~/ b); // 3 - Integer division (truncates)
17print(a % b); // 1 - Modulo (remainder)
18 
19// Integer division vs regular division
20print(10 / 3); // 3.3333... (returns double)
21print(10 ~/ 3); // 3 (returns int, truncates decimal)

HintIntegers are perfect for counting, indexing, and situations where decimal precision is not needed. Use ~/ for integer division to get a whole number result.

Double Type (double)

The double type represents 64-bit floating-point numbers (decimals). Use double when you need precision for calculations involving fractions, percentages, or measurements.

Working with Doubles

example.dart
1// Double declarations
2double price = 19.99;
3double temperature = 36.6;
4double pi = 3.14159;
5 
6// Scientific notation
7double speedOfLight = 3.0e8; // 3.0 × 10⁸ = 300,000,000
8double tiny = 1.5e-5; // 1.5 × 10⁻⁵ = 0.000015
9 
10// Double arithmetic
11double x = 10.5;
12double y = 3.2;
13 
14print(x + y); // 13.7 - Addition
15print(x - y); // 7.3 - Subtraction
16print(x * y); // 33.6 - Multiplication
17print(x / y); // 3.28125 - Division
18 
19// Precision considerations
20double result = 0.1 + 0.2;
21print(result); // 0.30000000000000004 (floating-point precision issue)
22print(result.toStringAsFixed(1)); // "0.3" (formatted)

HintDoubles are essential for precise calculations. Be aware of floating-point precision limitations when comparing decimal values.

The num Type

The num type is the parent type of both int and double. Use num when a variable could be either an integer or a double.

Using num

example.dart
1// num can hold both int and double
2num count = 10; // int
3num price = 19.99; // double
4 
5// Useful for functions that accept both types
6num add(num a, num b) {
7 return a + b;
8}
9 
10print(add(5, 3)); // 8 (int + int)
11print(add(5.5, 3.2)); // 8.7 (double + double)
12print(add(5, 3.2)); // 8.2 (int + double = double)
13 
14// Type checking
15num value = 42;
16print(value is int); // true
17print(value is double); // false
18print(value is num); // true
19 
20value = 42.0;
21print(value is int); // false
22print(value is double); // true

HintUse num for flexibility when you need to work with both integers and doubles. The result type depends on the operands.

Number Conversion and Parsing

Converting between number types and parsing strings to numbers are common operations in Dart applications.

Converting and Parsing Numbers

example.dart
1// Converting int to double
2int wholeNumber = 42;
3double decimal = wholeNumber.toDouble(); // 42.0
4 
5// Converting double to int (truncates decimal part)
6double price = 19.99;
7int rounded = price.toInt(); // 19 (truncates)
8int roundedUp = price.ceil(); // 20 (rounds up)
9int roundedDown = price.floor(); // 19 (rounds down)
10int roundedNearest = price.round(); // 20 (rounds to nearest)
11 
12// Parsing strings to numbers
13String ageText = '25';
14int age = int.parse(ageText); // 25
15 
16String priceText = '19.99';
17double productPrice = double.parse(priceText); // 19.99
18 
19// Safe parsing with tryParse (returns null if invalid)
20String invalid = 'abc';
21int? result = int.tryParse(invalid); // null (doesn't throw error)
22 
23String valid = '100';
24int? number = int.tryParse(valid); // 100
25 
26// Converting numbers to strings
27int count = 42;
28String countText = count.toString(); // "42"
29 
30double pi = 3.14159;
31String piText = pi.toString(); // "3.14159"
32String piFixed = pi.toStringAsFixed(2); // "3.14"
33String piPrecision = pi.toStringAsPrecision(3); // "3.14"

HintAlways use tryParse() when parsing user input to handle invalid data gracefully. Use toStringAsFixed() for consistent decimal formatting.

Common Number Operations

Dart provides many useful methods and operators for working with numbers.

Number Methods and Operations

example.dart
1// Absolute value
2int negative = -42;
3print(negative.abs()); // 42
4 
5// Power and square root (requires dart:math)
6import 'dart:math';
7 
8print(pow(2, 3)); // 8.0 (2³)
9print(sqrt(16)); // 4.0 (√16)
10 
11// Min and Max
12print(min(10, 5)); // 5
13print(max(10, 5)); // 10
14 
15// Rounding operations
16double value = 3.7;
17print(value.round()); // 4
18print(value.floor()); // 3
19print(value.ceil()); // 4
20print(value.truncate()); // 3
21 
22// Check if finite or infinite
23double finite = 42.0;
24double infinite = double.infinity;
25double notANumber = double.nan;
26 
27print(finite.isFinite); // true
28print(infinite.isInfinite); // true
29print(notANumber.isNaN); // true
30 
31// Clamping values (keeping within range)
32int score = 150;
33int clamped = score.clamp(0, 100); // 100 (limited to max 100)
34 
35double temperature = -5.0;
36double safe = temperature.clamp(0.0, 40.0); // 0.0 (limited to min 0)

HintThese methods help you perform common mathematical operations and validations on numbers.

Working with dart:math

The dart:math library provides advanced mathematical functions and constants.

Using dart:math Library

example.dart
1import 'dart:math';
2 
3// Mathematical constants
4print(pi); // 3.141592653589793
5print(e); // 2.718281828459045
6 
7// Trigonometric functions (angles in radians)
8print(sin(pi / 2)); // 1.0
9print(cos(0)); // 1.0
10print(tan(pi / 4)); // 1.0
11 
12// Exponential and logarithmic
13print(exp(1)); // 2.718... (e¹)
14print(log(e)); // 1.0 (natural log)
15 
16// Random numbers
17Random random = Random();
18int randomInt = random.nextInt(100); // 0 to 99
19double randomDouble = random.nextDouble(); // 0.0 to 1.0
20bool randomBool = random.nextBool(); // true or false
21 
22// Random in range
23int diceRoll = random.nextInt(6) + 1; // 1 to 6
24double percentage = random.nextDouble() * 100; // 0.0 to 100.0
25 
26// Seeded random (reproducible)
27Random seeded = Random(42);
28print(seeded.nextInt(100)); // Always same sequence with same seed

HintThe dart:math library is essential for advanced calculations, trigonometry, and generating random numbers.

Practical Examples

Real-world scenarios demonstrating number operations in Dart applications.

Real-World Number Usage

example.dart
1import 'dart:math';
2 
3// Calculate discount price
4double calculateDiscount(double price, int discountPercent) {
5 double discount = price * (discountPercent / 100);
6 double finalPrice = price - discount;
7 return double.parse(finalPrice.toStringAsFixed(2)); // Round to 2 decimals
8}
9 
10print(calculateDiscount(99.99, 20)); // 79.99
11 
12// Calculate BMI (Body Mass Index)
13double calculateBMI(double weightKg, double heightM) {
14 double bmi = weightKg / pow(heightM, 2);
15 return double.parse(bmi.toStringAsFixed(1));
16}
17 
18print(calculateBMI(70, 1.75)); // 22.9
19 
20// Generate random PIN
21String generatePIN(int length) {
22 Random random = Random();
23 String pin = '';
24 for (int i = 0; i < length; i++) {
25 pin += random.nextInt(10).toString();
26 }
27 return pin;
28}
29 
30print(generatePIN(4)); // e.g., "7392"
31 
32// Calculate compound interest
33double calculateCompoundInterest({
34 required double principal,
35 required double rate,
36 required int years,
37 int timesPerYear = 1,
38}) {
39 double amount = principal * pow(1 + (rate / timesPerYear), timesPerYear * years);
40 return double.parse(amount.toStringAsFixed(2));
41}
42 
43print(calculateCompoundInterest(
44 principal: 1000,
45 rate: 0.05, // 5%
46 years: 10,
47 timesPerYear: 12, // Monthly compounding
48)); // 1647.01

HintThese examples show how to use numbers in real applications: e-commerce calculations, health metrics, security, and financial computations.

Loot collected

Key takeaways
  • Use int for whole numbers and double for decimal numbers
  • The num type can hold both int and double values
  • Use ~/ for integer division and / for regular division
  • Always use tryParse() when parsing user input to handle errors gracefully
  • Be aware of floating-point precision issues when working with doubles
  • Use toStringAsFixed() to format numbers with specific decimal places
  • The dart:math library provides advanced mathematical functions and random number generation
  • Use clamp() to keep values within a specific range
  • Methods like round(), floor(), and ceil() help control decimal precision

Side quests

Practice exercises

1

Exercise 1: Temperature Converter

Write a function that converts Celsius to Fahrenheit. Formula: F = (C × 9/5) + 32

Reveal solution
solution.dart
1double celsiusToFahrenheit(double celsius) {
2 return (celsius * 9 / 5) + 32;
3}
4 
5print(celsiusToFahrenheit(0)); // 32.0
6print(celsiusToFahrenheit(100)); // 212.0
2

Exercise 2: Circle Calculator

Create a function that calculates the area of a circle given its radius. Formula: Area = π × r²

Reveal solution
solution.dart
1import 'dart:math';
2 
3double calculateCircleArea(double radius) {
4 return pi * pow(radius, 2);
5}
6 
7print(calculateCircleArea(5).toStringAsFixed(2)); // "78.54"
3

Exercise 3: Safe Division

Write a function that safely divides two numbers and returns null if division by zero is attempted.

Reveal solution
solution.dart
1double? safeDivide(num a, num b) {
2 if (b == 0) return null;
3 return a / b;
4}
5 
6print(safeDivide(10, 2)); // 5.0
7print(safeDivide(10, 0)); // null
4

Exercise 4: Random Range

Create a function that generates a random integer between min and max (inclusive).

Reveal solution
solution.dart
1import 'dart:math';
2 
3int randomInRange(int min, int max) {
4 Random random = Random();
5 return min + random.nextInt(max - min + 1);
6}
7 
8print(randomInRange(1, 10)); // Random number between 1 and 10
Party chat

Comments