parse static method

num parse(
  1. String input, [
  2. @deprecated num onError(
    1. String input
    )?
])

Parses a string containing a number literal into a number.

The method first tries to read the input as integer (similar to int.parse without a radix). If that fails, it tries to parse the input as a double (similar to double.parse). If that fails, too, it throws a FormatException.

Rather than throwing and immediately catching the FormatException, instead use tryParse to handle a potential parsing error.

For any number n, this function satisfies identical(n, num.parse(n.toString())) (except when n is a NaN double with a payload).

The onError parameter is deprecated and will be removed. Instead of num.parse(string, (string) { ... }), you should use num.tryParse(string) ?? (...).

Examples:

var value = num.parse('2021'); / 2021
value = num.parse('3.14'); / 3.14
value = num.parse('  3.14 \xA0'); / 3.14
value = num.parse('0.'); / 0.0
value = num.parse('.0'); / 0.0
value = num.parse('-1.e3'); / -1000.0
value = num.parse('1234E+7'); / 12340000000.0
value = num.parse('+.12e-9'); / 1.2e-10
value = num.parse('-NaN'); / NaN
value = num.parse('0xFF'); / 255
value = num.parse(double.infinity.toString()); / Infinity
value = num.parse('1f'); / Throws.

Implementation

static num parse(String input, [@deprecated num onError(String input)?]) {
  num? result = tryParse(input);
  if (result != null) return result;
  throw FormatException(input);
}