What is Type Conversion?
Type conversion (or type casting) is the process of changing a value from one data type to another. In Dart this is always explicit — you must intentionally convert a value; Dart will not silently convert types for you.
String to Number
// String → int
String s1 = '42';
int n1 = int.parse(s1);
print(n1 + 8); // 50
// String → double
String s2 = '3.14';
double n2 = double.parse(s2);
print(n2 * 2); // 6.28
// Safe parsing (no exception on failure)
int? safe = int.tryParse('abc');
print(safe); // null
Number to String
int n = 100;
double d = 3.14159;
String s1 = n.toString(); // '100'
String s2 = d.toString(); // '3.14159'
String s3 = d.toStringAsFixed(2); // '3.14'
String s4 = n.toRadixString(16); // '64' (hex)
print(s1 + ' dollars'); // 100 dollars
int to double
int i = 5;
double d = i.toDouble(); // 5.0
double d2 = i / 1; // also 5.0 (division always returns double)
print(d); // 5.0
double to int
double d = 9.99;
int i1 = d.toInt(); // 9 (truncates decimal)
int i2 = d.round(); // 10 (rounds to nearest)
int i3 = d.ceil(); // 10 (rounds up)
int i4 = d.floor(); // 9 (rounds down)
print('$i1 $i2 $i3 $i4'); // 9 10 10 9
Boolean Conversions
Dart does not automatically convert other types to bool. Use explicit comparisons:
int n = 0;
// bool b = n; ← ERROR in Dart
bool b = n != 0; // explicit conversion: false
bool b2 = n == 0; // true
String s = '';
bool isEmpty = s.isEmpty; // true
Full Example
void main() {
// Simulating user input as strings
String ageInput = '25';
String heightInput = '5.9';
int age = int.parse(ageInput);
double height = double.parse(heightInput);
print('Age: $age ($${age.runtimeType})');
print('Height: $height ($${height.runtimeType})');
// Convert back to string for display
String summary = 'Age $age, Height $${height.toStringAsFixed(1)} ft';
print(summary);
// int ↔ double
double ageDouble = age.toDouble();
int heightInt = height.toInt();
print('Age as double: $ageDouble');
print('Height as int: $heightInt');
}
Output:
Age: 25 (int)
Height: 5.9 (double)
Age 25, Height 5.9 ft
Age as double: 25.0
Height as int: 5
💪 Exercise
- Parse
'100' and '45.5' from strings, add them, and print the result.
- Convert the double
7.8 to an int using round(), floor(), and ceil() — print all three.
- Convert the integer
255 to its hexadecimal string representation.
🧠 Quiz
1. What does double.toInt() do to 3.9?
- A) Returns 4 (rounds)
- B) Returns 3 (truncates) ✅
- C) Returns 3.9
- D) Throws an error
2. Which method safely converts a string to int without throwing an exception?
- A) int.parse()
- B) int.convert()
- C) int.tryParse() ✅
- D) int.cast()
Summary
Dart type conversion is always explicit. Convert strings to numbers with int.parse() / double.parse(). Convert numbers to strings with toString() / toStringAsFixed(). Convert between int and double with toDouble() / toInt(). Use tryParse() for safe parsing that returns null on failure.