278

I would like to parse strings like 1 or 32.23 into integers and doubles. How can I do this with Dart?

Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
  • 1
    apart from below answers if your string has letters you can do like this: https://stackoverflow.com/a/61401948/614026 – temirbek Sep 10 '20 at 08:41

11 Answers11

421

You can parse a string into an integer with int.parse(). For example:

var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345

Note that int.parse() accepts 0x prefixed strings. Otherwise the input is treated as base-10.

You can parse a string into a double with double.parse(). For example:

var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45

parse() will throw FormatException if it cannot parse the input.

Kai Sellgren
  • 27,954
  • 10
  • 75
  • 87
Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
  • 3
    How should you parse an integer from a string that contains invalid characters later on? E.g., "-01:00", where I want to get -1, or "172 apples" where I would expect to get 172. In JavaScript parseInt("-01:00") works just fine but Dart gives an error. Is there any easy way without checking manually character-by-character? Thanks. – user1596274 Aug 18 '20 at 14:29
148

In Dart 2 int.tryParse is available.

It returns null for invalid inputs instead of throwing. You can use it like this:

int val = int.tryParse(text) ?? defaultValue;
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
62

Convert String to Int

var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
print(myInt.runtimeType);

Convert String to Double

var myDouble = double.parse('123.45');
assert(myInt is double);
print(myDouble); // 123.45
print(myDouble.runtimeType);

Example in DartPad

screenshot of dartpad

FuXiang Shu
  • 100
  • 8
Javeed Ishaq
  • 6,024
  • 6
  • 41
  • 60
16

As per dart 2.6

The optional onError parameter of int.parse is deprecated. Therefore, you should use int.tryParse instead.

Note: The same applies to double.parse. Therefore, use double.tryParse instead.

  /**
   * ...
   *
   * The [onError] parameter is deprecated and will be removed.
   * Instead of `int.parse(string, onError: (string) => ...)`,
   * you should use `int.tryParse(string) ?? (...)`.
   *
   * ...
   */
  external static int parse(String source, {int radix, @deprecated int onError(String source)});

The difference is that int.tryParse returns null if the source string is invalid.

  /**
   * Parse [source] as a, possibly signed, integer literal and return its value.
   *
   * Like [parse] except that this function returns `null` where a
   * similar call to [parse] would throw a [FormatException],
   * and the [source] must still not be `null`.
   */
  external static int tryParse(String source, {int radix});

So, in your case it should look like:

// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345

// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
  print(parsedValue2); // null
  //
  // handle the error here ...
  //
}
Ilker Cat
  • 1,862
  • 23
  • 17
15
 void main(){
  var x = "4";
  int number = int.parse(x);//STRING to INT

  var y = "4.6";
  double doubleNum = double.parse(y);//STRING to DOUBLE

  var z = 55;
  String myStr = z.toString();//INT to STRING
}

int.parse() and double.parse() can throw an error when it couldn't parse the String

  • 2
    `int.parse()` and `double.parse()` can throw an error when it couldn't parse the String. Please elaborate on your answer so that others can learn and understand dart better. – josxha Jun 26 '20 at 15:14
  • 1
    Thank-you for mentioning it josxha, I am an absolute beginner in Dart and I'm trying my best to help others, Well I thought it would be the simplest answer, anyway Thanks!! – Rajdeep12345678910 Jun 28 '20 at 07:57
12

Above solutions will not work for String like:

String str = '123 km';

So, the answer in a single line, that works in every situation for me will be:

int r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), '')) ?? defaultValue;
or
int? r = int.tryParse(str.replaceAll(RegExp(r'[^0-9]'), ''));

But be warned that it will not work for the below kind of string

String problemString = 'I am a fraction 123.45';
String moreProblem = '20 and 30 is friend';

If you want to extract double which will work in every kind then use:

double d = double.tryParse(str.replaceAll(RegExp(r'[^0-9\.]'), '')) ?? defaultValue;
or
double? d = double.tryParse(str.replaceAll(RegExp(r'[^0-9\.]'), ''));

This will work for problemString but not for moreProblem.

Zihan
  • 668
  • 8
  • 19
7

you can parse string with int.parse('your string value');.

Example:- int num = int.parse('110011'); print(num); // prints 110011 ;

Rajni Gujarati
  • 2,709
  • 1
  • 10
  • 16
5

If you don't know whether your type is string or int you can do like this:

int parseInt(dynamic s){
  if(s.runtimeType==String) return int.parse(s);
  return s as int;
}

For double:

double parseDouble(dynamic s){
  if(s.runtimeType==String) return double.parse(s);
  return s as double;
}

Therefore you can do parseInt('1') or parseInt(1)

Arfina Arfwani
  • 166
  • 3
  • 3
4
void main(){
String myString ='111';
int data = int.parse(myString);
print(data);
}
Rishita Joshi
  • 203
  • 2
  • 3
1

You can do this for easy conversion like this

Example Code Here

void main() {
  var myInt = int.parse('12345');
 var number = myInt.toInt();
  print(number); // 12345
  print(number.runtimeType);  // int
  
  
    var myDouble = double.parse('123.45');
  var double_int = myDouble.toDouble();
  print(double_int); // 123.45
   print(double_int.runtimeType);  
}
0
String age = stdin.readLineSync()!; // first take the input from user in string form
int.parse(age);  // then parse it to integer that's it
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Siraj Ahmed
  • 128
  • 2
  • 6