Dart num.parse()
Syntax & Examples


num.parse() static-method

The `parse` static method in Dart parses a string containing a number literal into a number.


Syntax of num.parse()

The syntax of num.parse() static-method is:

 num parse(String input, [ num onError(String input) ]) 

This parse() static-method of num parses a string containing a number literal into a number.

Parameters

ParameterOptional/RequiredDescription
inputrequiredThe string to parse as a number.
onErroroptionalA function that returns a default value or throws if parsing fails. If not provided, it defaults to null.

Return Type

num.parse() returns value of type num.



✐ Examples

1 Parsing a valid number string

In this example,

  1. We create a string variable input with the value '123.45'.
  2. We use the parse() method to parse it as a number.
  3. We then print the parsed value to standard output.

Dart Program

void main() {
  String input = '123.45';
  num parsedValue = num.parse(input);
  print('Parsed value: $parsedValue');
}

Output

Parsed value: 123.45

2 Parsing an invalid number string with error handling

In this example,

  1. We create a string variable input with the value 'abc'.
  2. We use the parse() method with an error handling function that returns 0 if parsing fails.
  3. We then print the parsed value (or default value) to standard output.

Dart Program

void main() {
  String input = 'abc';
  num parsedValue = num.parse(input, (String input) => 0);
  print('Parsed value with error handling: $parsedValue');
}

Output

Script error.

Summary

In this Dart tutorial, we learned about parse() static-method of num: the syntax and few working examples with output and detailed explanation for each example.