Number Parsing in Dart
Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Dart.
To run the program:
In Dart, number parsing is provided by the dart:core
library, which is automatically imported in all Dart programs. The double.parse()
and int.parse()
methods are used for parsing floating-point and integer values respectively.
For parsing floating-point numbers, double.parse()
is used. It doesn’t require a precision parameter like in some other languages.
For integer parsing, int.parse()
is used. By default, it assumes base 10, but you can specify a different radix as an optional parameter.
Dart doesn’t have separate signed and unsigned integer types, so there’s no separate method for parsing unsigned integers. All integers in Dart are signed 64-bit (on most platforms).
For hexadecimal numbers, you can use int.parse()
with a radix of 16, or include the ‘0x’ prefix in the string and omit the radix parameter.
Unlike some other languages, Dart doesn’t have a separate convenience function for parsing integers (like atoi
in C). The int.parse()
method serves this purpose.
When parsing fails due to invalid input, Dart throws a FormatException
instead of returning an error value. It’s good practice to handle this exception when parsing user input or other potentially unreliable sources.
Next, we’ll look at another common parsing task: URLs.