Dart double.parse()
Syntax & Examples
double.parse() static-method
The `parse` method is used to parse a string as a double literal and return its numerical value.
Syntax of double.parse()
The syntax of double.parse() static-method is:
double parse(String source, [ double onError(String source) ])
This parse() 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 |
onError | optional | a function that returns a default value if parsing fails |
Return Type
double.parse() returns value of type double
.
✐ Examples
1 Parse a double from a string (value1)
In this example,
- We define a string
value1
with the value'3.14'
. - We use the
double.parse()
method to parsevalue1
as a double. - The result is stored in the variable
result1
. - We print the result to standard output.
Dart Program
void main() {
String value1 = '3.14';
double result1 = double.parse(value1);
print('Result 1: $result1');
}
Output
Result 1: 3.14
2 Parse a double from a string (value2)
In this example,
- We define a string
value2
with the value'10'
. - We use the
double.parse()
method to parsevalue2
as a double. - The result is stored in the variable
result2
. - We print the result to standard output.
Dart Program
void main() {
String value2 = '10';
double result2 = double.parse(value2);
print('Result 2: $result2');
}
Output
Result 2: 10
3 Parse a double from an invalid string
In this example,
- We define a string
value3
with the value'abc'
. - We use the
double.parse()
method to parsevalue3
as a double. - Since
value3
cannot be parsed as a double, we provide a custom error handling function that returns0.0
. - The result is stored in the variable
result3
. - We print the result to standard output.
Dart Program
void main() {
String value3 = 'abc';
double result3 = double.parse(value3);
print('Result 3: $result3');
}
Output
Script error.
Summary
In this Dart tutorial, we learned about parse() static-method of double: the syntax and few working examples with output and detailed explanation for each example.