Type Conversion

Type conversion in Dart is like translating between different languages - sometimes you need to convert data from one type to another to make your program work correctly. Dart provides several built-in methods to convert between common data types.

Converting to String

You can convert numbers and other types to strings using the toString() method:

int age = 25;
double price = 99.99;
bool isActive = true;

String ageStr = age.toString();        // "25"
String priceStr = price.toString();    // "99.99"
String activeStr = isActive.toString(); // "true"

print("Age: $ageStr");
print("Price: \$${priceStr}");

Converting to Numbers

String to int

Use int.parse() to convert a string to an integer:

String numberStr = "42";
int number = int.parse(numberStr);
print(number); // 42

// Handle invalid strings with try-catch
String invalidStr = "abc";
try {
  int invalid = int.parse(invalidStr);
} catch (e) {
  print("Cannot convert '$invalidStr' to int");
}

String to double

Use double.parse() to convert a string to a double:

String priceStr = "19.99";
double price = double.parse(priceStr);
print(price); // 19.99

String piStr = "3.14159";
double pi = double.parse(piStr);
print(pi); // 3.14159

Safe Conversion with tryParse

Use tryParse() methods for safer conversion that returns null instead of throwing an error:

String validNumber = "123";
String invalidNumber = "abc";

int? result1 = int.tryParse(validNumber);   // 123
int? result2 = int.tryParse(invalidNumber); // null

if (result1 != null) {
  print("Valid number: $result1");
}

if (result2 == null) {
  print("Invalid number format");
}

Converting Between Numbers

int to double

int wholeNumber = 10;
double decimal = wholeNumber.toDouble();
print(decimal); // 10.0

double to int

double decimal = 15.7;
int rounded = decimal.round();  // 16 (rounds to nearest)
int floored = decimal.floor();  // 15 (rounds down)
int ceiled = decimal.ceil();    // 16 (rounds up)
int truncated = decimal.toInt(); // 15 (removes decimal part)

print("Original: $decimal");
print("Rounded: $rounded");
print("Floored: $floored");
print("Ceiled: $ceiled");
print("Truncated: $truncated");

Common Type Conversion Methods

From TypeTo TypeMethodExample
intStringtoString()42.toString()"42"
doubleStringtoString()3.14.toString()"3.14"
boolStringtoString()true.toString()"true"
Stringintint.parse()int.parse("42")42
Stringdoubledouble.parse()double.parse("3.14")3.14
intdoubletoDouble()42.toDouble()42.0
doubleinttoInt()3.14.toInt()3

Practical Example

Here's a practical example showing type conversion in action:

void main() {
  // Getting user input (usually comes as String)
  String userAge = "25";
  String userHeight = "5.8";
  
  // Convert to appropriate types
  int age = int.parse(userAge);
  double height = double.parse(userHeight);
  
  // Perform calculations
  double bmi = calculateBMI(height, 70.5);
  
  // Convert back to string for display
  String result = "Age: ${age.toString()}, BMI: ${bmi.toStringAsFixed(2)}";
  print(result);
}

double calculateBMI(double height, double weight) {
  return weight / (height * height);
}

Remember: Always be careful when converting types, especially from strings to numbers, as invalid input can cause runtime errors. Use tryParse() methods when you're unsure about the input format!