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.

// The dart:core library provides number parsing functionality
import 'dart:core';

void main() {
  // With double.parse, we can convert a string to a double
  double f = double.parse('1.234');
  print(f);

  // For parsing integers, we use int.parse
  int i = int.parse('123');
  print(i);

  // int.parse will recognize hex-formatted numbers with the '0x' prefix
  int d = int.parse('0x1c8', radix: 16);
  print(d);

  // There's no separate method for parsing unsigned integers in Dart
  // as all integers are signed. However, you can use int.parse
  int u = int.parse('789');
  print(u);

  // int.parse is used for basic base-10 int parsing
  int k = int.parse('135');
  print(k);

  // Parse functions throw a FormatException on bad input
  try {
    int.parse('wat');
  } catch (e) {
    print(e);
  }
}

To run the program:

$ dart run number_parsing.dart
1.234
123
456
789
135
FormatException: Invalid radix-10 number (at character 1)
wat
^

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.