Dart int.parse()
Syntax & Examples
int.parse() static-method
The `parse` method in Dart parses a string as a, possibly signed, integer literal and returns its value.
Syntax of int.parse()
The syntax of int.parse() static-method is:
int parse(String source, { int radix, int onError(String source) })
This parse() static-method of int parse source as a, possibly signed, integer literal and return its value.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
source | required | The string to parse as an integer. |
radix | optional | The radix of the parsed integer. If not provided, it defaults to 10. |
onError | optional | A function that handles errors encountered during parsing. If not provided, an exception is thrown. |
Return Type
int.parse() returns value of type int
.
✐ Examples
1 Parsing a positive integer
In this example,
- We define a string
source
containing the integer123
. - We use the
parse
method to parse the string as an integer. - We print the parsed integer value to standard output.
Dart Program
void main() {
String source = '123';
int value = int.parse(source);
print('Parsed integer value: $value');
}
Output
Parsed integer value: 123
2 Parsing a negative integer
In this example,
- We define a string
source
containing the integer-456
. - We use the
parse
method to parse the string as an integer. - We print the parsed integer value to standard output.
Dart Program
void main() {
String source = '-456';
int value = int.parse(source);
print('Parsed integer value: $value');
}
Output
Parsed integer value: -456
3 Parsing a hexadecimal integer
In this example,
- We define a string
source
containing the hexadecimal integerFF
. - We use the
parse
method with a radix of16
to parse the string as an integer. - We print the parsed integer value to standard output.
Dart Program
void main() {
String source = 'FF';
int value = int.parse(source, radix: 16);
print('Parsed integer value: $value');
}
Output
Parsed integer value: 255
Summary
In this Dart tutorial, we learned about parse() static-method of int: the syntax and few working examples with output and detailed explanation for each example.