The `tryParse` method attempts to parse a string as a double literal and returns its numeric value if successful; otherwise, it returns null.
The syntax of double.tryParse() static-method is:
double tryParse(String source)
This tryParse() static-method of double parse source
as an double literal and return its value.
Parameter | Optional/Required | Description |
---|---|---|
source | required | the string to parse as a double |
double.tryParse() returns value of type double
.
In this example,
input1
and input2
.tryParse
method to attempt parsing input1
and input2
as double literals.void main() {
String input1 = '3.14';
String input2 = '10';
double? result1 = double.tryParse(input1);
double? result2 = double.tryParse(input2);
print('Parsed value from $input1: $result1');
print('Parsed value from $input2: $result2');
}
Parsed value from 3.14: 3.14 Parsed value from '10': 10
In this example,
input1
with a non-numeric value 'hello' and input2
with a valid double literal '3.14'.tryParse
method to attempt parsing input1
and input2
as double literals.void main() {
String input1 = 'hello';
String input2 = '3.14';
double? result1 = double.tryParse(input1);
double? result2 = double.tryParse(input2);
print('Parsed value from $input1: $result1');
print('Parsed value from $input2: $result2');
}
Parsed value from hello: null Parsed value from '3.14': 3.14
In this Dart tutorial, we learned about tryParse() static-method of double: the syntax and few working examples with output and detailed explanation for each example.