Dart double.tryParse()
Syntax & Examples
double.tryParse() static-method
The `tryParse` method attempts to parse a string as a double literal and returns its numeric value if successful; otherwise, it returns null.
Syntax of double.tryParse()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
source | required | the string to parse as a double |
Return Type
double.tryParse() returns value of type double
.
✐ Examples
1 Successful parsing
In this example,
- We create two string inputs
input1
andinput2
. - We use the
tryParse
method to attempt parsinginput1
andinput2
as double literals. - If parsing is successful, the method returns the parsed double value; otherwise, it returns null.
- We print the parsed values to standard output.
Dart Program
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');
}
Output
Parsed value from 3.14: 3.14 Parsed value from '10': 10
2 Unsuccessful parsing
In this example,
- We create two string inputs
input1
with a non-numeric value 'hello' andinput2
with a valid double literal '3.14'. - We use the
tryParse
method to attempt parsinginput1
andinput2
as double literals. - If parsing is successful, the method returns the parsed double value; otherwise, it returns null.
- We print the parsed values to standard output.
Dart Program
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');
}
Output
Parsed value from hello: null Parsed value from '3.14': 3.14
Summary
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.