Integer (int)
The int type stores whole numbers (positive, negative, or zero) without a decimal point. Dart integers can be arbitrarily large.
int a = 100;
int b = -50;
int hex = 0xFF; // hexadecimal = 255
int binary = 0b1010; // binary = 10 (Dart 3+)
print(a + b); // 50
print(hex); // 255
Double
The double type stores 64-bit floating-point numbers (numbers with decimals).
double pi = 3.14159;
double e = 2.71828;
double sci = 1.5e6; // scientific notation = 1500000.0
print(pi.toStringAsFixed(2)); // 3.14
The num Type
num is the parent type of both int and double. Use it when a variable might hold either type:
num x = 10; // int
x = 3.14; // now double — allowed with num
print(x); // 3.14
Parsing Numbers
Convert strings to numbers using int.parse() and double.parse():
String s1 = '42';
String s2 = '3.14';
int n1 = int.parse(s1); // 42
double n2 = double.parse(s2); // 3.14
// Safe parsing (returns null on failure):
int? n3 = int.tryParse('abc'); // null
print(n3 ?? 0); // 0
Math Operations
| Operator | Description | Example | Result |
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | Division (double) | 10 / 3 | 3.333 |
~/ | Integer division | 10 ~/ 3 | 3 |
% | Modulo (remainder) | 10 % 3 | 1 |
dart:math Library
import 'dart:math';
void main() {
print(sqrt(16)); // 4.0
print(pow(2, 8)); // 256.0
print(max(10, 20)); // 20
print(min(10, 20)); // 10
print(pi); // 3.141592653589793
// Random number 0–99
var random = Random();
print(random.nextInt(100));
}
Example
void main() {
double principal = 1000.0;
double rate = 5.0;
int years = 3;
double interest = (principal * rate * years) / 100;
double total = principal + interest;
print('Principal: \$$${principal.toStringAsFixed(2)}');
print('Interest: \$$${interest.toStringAsFixed(2)}');
print('Total after $years years: \$$${total.toStringAsFixed(2)}');
}
Output:
Principal: $1000.00
Interest: $150.00
Total after 3 years: $1150.00
💪 Exercise
- Write a program to calculate the area and circumference of a circle (use
dart:math for pi).
- Parse the string
'2024' to an integer and print it doubled.
- Find the remainder when 100 is divided by 7 using the
% operator.
🧠 Quiz
1. What operator performs integer (truncating) division in Dart?
2. Which method safely parses a string to int (returning null on failure)?
- A) int.parse()
- B) int.tryParse() ✅
- C) int.convert()
- D) int.from()
Summary
Dart supports int for whole numbers and double for decimals. Use num when the type can be either. Parse strings with int.parse() or the safe int.tryParse(). Import dart:math for mathematical functions like sqrt(), pow(), and Random().