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

ParameterOptional/RequiredDescription
sourcerequiredthe string to parse as a double
onErroroptionala 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,

  1. We define a string value1 with the value '3.14'.
  2. We use the double.parse() method to parse value1 as a double.
  3. The result is stored in the variable result1.
  4. 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,

  1. We define a string value2 with the value '10'.
  2. We use the double.parse() method to parse value2 as a double.
  3. The result is stored in the variable result2.
  4. 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,

  1. We define a string value3 with the value 'abc'.
  2. We use the double.parse() method to parse value3 as a double.
  3. Since value3 cannot be parsed as a double, we provide a custom error handling function that returns 0.0.
  4. The result is stored in the variable result3.
  5. 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.