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
Parameter | Optional/Required | Description |
---|---|---|
input | required | The 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,
- We create a string variable
input1
with the value '123' and another variableinput2
with the value '3.14'. - We use the
tryParse()
method to parse these strings into numbers. - 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,
- We create a string variable
input
with the value 'abc', which is not a valid number literal. - We use the
tryParse()
method to parse this string into a number. - 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.