Low Orbit Flux Logo 2 D

Dart How to Convert String to Number (int or double)

Converting a string to a number in Dart is easy. We are going to show you how to convert to an int or a double. We will also show you how to convert back to a string and how to show what type a variable is.

Dart - Convert String to Int

Converting a string to an int is easy. You just call the int.parse() function and pass your string. It will return an int. You can verify this by printing runtimeType. You can also do this with a string literal.

var x = "12345";
var y = int.parse(x);       // convert
print(y);                   // print the value
print(y.runtimeType);       // print the type

Dart - Convert String to Double

You can convert a double to a string fairly easily as shown below. Just use the double.parse() function. You can verify the same way that we did above with the int.

var x = "123.45";
var y = double.parse(x);    // convert
print(y);                   // print the value
print(y.runtimeType);       // print the type

Convert int or double to String

Here are some examples showing how to convert a number to a string. You can use variables or not.

String s1 = 1.toString();
String s2 = 3.14159.toStringAsFixed(2);

var a = 1;
var b = 3.14159;

String s3 = a.toString();
String s4 = b.toStringAsFixed(2);    // 2 decimals
String s5 = b.toString();     

print(s1);                            // print the value
print(s2);                            // print the value
print(s3);                            // print the value
print(s4);                            // print the value
print(s5);                            // print the value
print(s1.runtimeType);       // print the type
print(s2.runtimeType);       // print the type
print(s3.runtimeType);       // print the type
print(s4.runtimeType);       // print the type
print(s5.runtimeType);       // print the type