Skip to main content

Introduction

Type conversion (also called type casting) is the process of converting a value from one data type to another. In Dart, you’ll often need to convert between types, such as turning a String into an int, or an int into a double.
Dart performs explicit type conversion - you must explicitly convert types using built-in methods. This prevents accidental type-related bugs.

Common Type Conversions

String → int

Parse text to integer

int → String

Convert number to text

int → double

Convert integer to decimal

double → int

Convert decimal to integer

String → double

Parse text to decimal

double → String

Convert decimal to text

String to int Conversion

Use int.parse() to convert a String containing a number into an integer:
int.parse() will throw an error if the string doesn’t contain a valid integer. For example, int.parse('hello') will crash your program.

Safe Parsing with tryParse

For safer parsing that won’t crash your program, use int.tryParse():

int to String Conversion

Use .toString() to convert any number to a String:

Working with Large Numbers

int to double Conversion

Use .toDouble() to convert an integer to a double (decimal number):
Converting to double is useful when you need decimal precision in calculations, even if your starting value is a whole number.

double to int Conversion

Use .toInt() to convert a double to an integer. This truncates the decimal part (doesn’t round):
.toInt() truncates (cuts off) the decimal part, it doesn’t round. For example:
  • 3.9.toInt() returns 3 (not 4)
  • 3.1.toInt() returns 3
  • -3.9.toInt() returns -3

Rounding Doubles to Integers

If you want to round instead of truncate, use these methods:

String to double Conversion

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

Complete Conversion Example

Here’s a comprehensive example showing all the common conversions:

Practical Use Cases

User Input Conversion

Calculations with Mixed Types

Formatting Numbers for Display

Conversion Methods Summary

Error Handling

Always validate string input before parsing to avoid runtime errors:

Key Takeaways

  • Use int.parse() or int.tryParse() to convert String to int
  • Use double.parse() or double.tryParse() to convert String to double
  • Use .toString() to convert any number to String
  • Use .toDouble() to convert int to double
  • Use .toInt() to convert double to int (truncates decimals)
  • Use .round(), .floor(), or .ceil() for rounding doubles
  • Always handle potential parsing errors with tryParse() methods

Next Steps

Now that you understand type conversions, you’re ready to explore operators and how to perform calculations and comparisons in Dart.