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
Parameter | Optional/Required | Description |
---|---|---|
input | required | The string to parse as a number. |
onError | optional | A 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,
- We create a string variable
input
with the value '123.45'. - We use the
parse()
method to parse it as a number. - 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,
- We create a string variable
input
with the value 'abc'. - We use the
parse()
method with an error handling function that returns 0 if parsing fails. - 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.