toInt function

int toInt(
  1. String input, {
  2. String locale = 'en_US',
})

Attempts to cast a String to an integer using locale or Dart int cast.

  • input String that can be cast to an integer.

Returns int if string is a valid integer.

Throws FormatException if String is not a valid integer.

Implementation

int toInt(String input, {String locale = 'en_US'}) {
  final String normalized = unorm.nfkd(input);

  String numberString = normalized.replaceAll(RegExp(r'\D'), '');

  if (numberString.isEmpty) {
    throw FormatException('Invalid integer string: $input');
  }

  try {
    final format = NumberFormat.decimalPattern(locale);
    return format.parse(numberString).toInt();
  } on FormatException {
    numberString = numberString.replaceAll(',', '');
    return int.parse(numberString);
  }
}