Dart num.tryParse()
Syntax & Examples


num.tryParse() static-method

The `tryParse` static method in Dart parses a string containing a number literal into a number.


Syntax of num.tryParse()

The syntax of num.tryParse() static-method is:

 num tryParse(String input) 

This tryParse() static-method of num parses a string containing a number literal into a number.

Parameters

ParameterOptional/RequiredDescription
inputrequiredThe string input containing a number literal.

Return Type

num.tryParse() returns value of type num.



✐ Examples

1 Parsing a valid number string

In this example,

  1. We create a string variable input1 with the value '123' and another variable input2 with the value '3.14'.
  2. We use the tryParse() method to parse these strings into numbers.
  3. We then print the parsed values to standard output.

Dart Program

void main() {
  String input1 = '123';
  String input2 = '3.14';
  num? result1 = num.tryParse(input1);
  num? result2 = num.tryParse(input2);
  print('Parsed value : $result1');
  print('Parsed value : $result2');
}

Output

Parsed value : 123
Parsed value : 3.14

2 Parsing an invalid number string

In this example,

  1. We create a string variable input with the value 'abc', which is not a valid number literal.
  2. We use the tryParse() method to parse this string into a number.
  3. Since 'abc' cannot be parsed into a number, the result is null.

Dart Program

void main() {
  String input = 'abc';
  num? result = num.tryParse(input);
  print('Parsed value : $result');
}

Output

Parsed value : null

Summary

In this Dart tutorial, we learned about tryParse() static-method of num: the syntax and few working examples with output and detailed explanation for each example.