parse method

Decimal parse(
  1. String amount
)

Parses the string for an amount using the currency object attached to the MoneyFormatter instance. If the string was parsed correctly, then a Decimal is returned with the amount set correctly. If the string failed to be parsed, then a MoneyParseException is thrown, with the message of the string set to one of the following:

  • Unexpected grouping separator character ',' for input string '...'
  • Invalid character '?' for input string '...'
  • Too many fractional digits for input string '...'
  • Too many digits for input string '...'
  • Unexpected decimal separator character '.' for input string '...'
  • Digits expected, none found for input string '...'

Implementation

Decimal parse(String amount) {
  var s = amount;
  var builder = DecimalBuilder(_currency.exponent, s.startsWith('-'));
  s = s.removePrefix('-');
  s = s.removePrefix(_currency.symbolPrefix);
  s = s.removeSuffix(_currency.symbolSuffix);

  try {
    for (var i = 0; i < s.length; i++) {
      var c = s[i];
      var codeUnit = c.codeUnitAt(0);
      if (codeUnit >= 0x30 && codeUnit <= 0x39) {
        builder.addDigit(c);
      } else {
        switch (c) {
          case ',':
            if (builder.isFractional) {
              throw FormatException('Unexpected grouping separator '
                  'character \',\'');
            }
            break;
          case '.':
            builder.setFractional();
            break;
          default:
            throw FormatException('Invalid character \'$c\'');
        }
      }
    }
    return builder.build();
  } on FormatException catch (e) {
    throw MoneyParseException(e.message + ' for input string \'$amount\'');
  }
}