Dart BigInt.tryParse()
Syntax & Examples
BigInt.tryParse() static-method
The BigInt static parse() method parses the given string source as a, possibly signed, integer literal and returns its value.
Syntax of BigInt.tryParse()
The syntax of BigInt.tryParse() static-method is:
BigInt tryParse(String source, { int radix })
This tryParse() static-method of BigInt parses source
as a, possibly signed, integer literal and returns its value.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
source | required | the string to attempt parsing as an integer |
radix | optional | the base of the numeral system used in source (defaults to 10 if not provided) |
Return Type
BigInt.tryParse() returns value of type BigInt
.
✐ Examples
1 Parsing a number
In this example,
- We create a string
numberStr
with the value '12345'. - We use the
tryParse()
method to attempt parsing the string as an integer and store the result in a nullable BigInt variablenumber
. - We check if the parsing was successful by ensuring
number
is not null, then print the parsed number to standard output. If parsing fails, we print 'Invalid input'.
Dart Program
void main() {
String numberStr = '12345';
BigInt? number = BigInt.tryParse(numberStr);
if (number != null) {
print('Parsed number: $number');
} else {
print('Invalid input');
}
}
Output
Parsed number: 12345
2 Parsing a character code
In this example,
- We create a string
charStr
with the value 'A'. - We use the
tryParse()
method with a radix of 16 (hexadecimal) to attempt parsing the string as a hexadecimal integer and store the result in a nullable BigInt variablecharCode
. - We check if the parsing was successful by ensuring
charCode
is not null, then print the parsed character code to standard output. If parsing fails, we print 'Invalid input'.
Dart Program
void main() {
String charStr = 'A';
BigInt? charCode = BigInt.tryParse(charStr, radix: 16);
if (charCode != null) {
print('Parsed character code: $charCode');
} else {
print('Invalid input');
}
}
Output
Parsed character code: 10
3 Parsing a binary number
In this example,
- We create a string
binaryStr
with the value '1010'. - We use the
tryParse()
method with a radix of 2 (binary) to attempt parsing the string as a binary integer and store the result in a nullable BigInt variabledecimalValue
. - We check if the parsing was successful by ensuring
decimalValue
is not null, then print the parsed binary number to decimal form to standard output. If parsing fails, we print 'Invalid input'.
Dart Program
void main() {
String binaryStr = '1010';
BigInt? decimalValue = BigInt.tryParse(binaryStr, radix: 2);
if (decimalValue != null) {
print('Parsed binary to decimal: $decimalValue');
} else {
print('Invalid input');
}
}
Output
Parsed binary to decimal: 10
Summary
In this Dart tutorial, we learned about tryParse() static-method of BigInt: the syntax and few working examples with output and detailed explanation for each example.