Dart Conversions
A conversion changes a value from one type to a new type. Dart makes a conversion only when the code names one.
A double becomes an int
toInt() drops the decimal part of a double. The value 9.99 becomes 9.
void main() {
var price = 9.99;
print(price.toInt());
}An int becomes a double
toDouble() gives an int a decimal part. The value 4 prints as 4.0.
void main() {
var count = 4;
print(count.toDouble());
}Text becomes numbers
parse reads a number out of a string. Adding 1 and 0.5 proves both results are numbers.
void main() {
var whole = int.parse('42');
print(whole + 1);
var decimal = double.parse('2.5');
print(decimal + 0.5);
}A number becomes text
toString() turns a number into a string. The String annotation accepts the result because the result is text.
void main() {
var score = 95;
String label = score.toString();
print(label);
}Example
void main() {
var price = 12.8;
print(price.toInt());
var count = 3;
print(count.toDouble());
var total = int.parse('20');
print(total + 5);
String label = 100.toString();
print(label);
}Key points
- Use toInt() to turn a double into an int.
- Use toDouble() to turn an int into a double.
- Use int.parse to read a whole number out of a string.
- Use double.parse to read a decimal number out of a string.
- Use toString() to turn a number into a string.
- A conversion builds a new value and leaves the first value as it was.
In this example, price.toInt() drops the decimal part and prints 12. count.toDouble() prints 3.0. int.parse reads 20 out of the string, and adding 5 prints 25. The last lines turn 100 into text and print that text.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
Which call turns the string '42' into the int 42?