parse method

Money parse(
  1. String monetaryAmountWithIsoCode, {
  2. String? pattern,
})

Parses a string containing a money amount including a currency isoCode.

Provided the passed currency isoCode is a Currency listed in CommonCurrencies or belongs to a Currency that has been registered via Currencies.register or Currencies.registerList then this method will return a Money instance of that Currency type.

An UnknownCurrencyException is thrown if the monetaryAmountWithIsoCode does not contain a known currency.

monetaryAmountWithIsoCode is the monetary value that you want parsed.

The pattern is the pattern to use when parsing the monetaryAmountWithIsoCode. The pattern is optional and if not passed then the default pattern registered with the Currency will be used to parse the monetaryAmountWithIsoCode.

If the number of minorUnits in monetaryAmountWithIsoCode exceeds the Currencys precision then excess digits will be ignored.

A MoneyParseException is thrown if the monetaryAmountWithIsoCode doesn't match the pattern.

Currency usd = Currency.create('USD', 2);
Currency aud = Currency.create('AUD', 2);
Currencies().registerList([usd, aud]);
final usdAmount = Currencies().parse(r'$USD1500.0');

See: Currencies.register Currencies.registerList Currencies.find

Implementation

Money parse(String monetaryAmountWithIsoCode, {String? pattern}) {
  Currency? currency;
  if (pattern == null) {
    /// No pattern? so find the currency based on the currency
    /// isoCode in the [monetaryAmount].
    currency = findByCode(monetaryAmountWithIsoCode);
  } else {
    final codeLength = _getCodeLength(pattern);

    if (codeLength < 2) {
      throw MoneyParseException(
          'The Country IsoCode length (e.g. CC) must be at '
          'least 2 characters long');
    }

    final isoCode = _extractIsoCode(monetaryAmountWithIsoCode, codeLength);

    currency = find(isoCode);
  }

  if (currency == null) {
    throw UnknownCurrencyException(monetaryAmountWithIsoCode);
  }

  pattern ??= currency.pattern;

  var monetaryAmount = monetaryAmountWithIsoCode;

  if (!_containsCode(pattern)) {
    /// The default patterns often don't contain a currency
    /// isoCode so as a conveniencce we strip the isoCode out of the
    /// [monetaryAmount]. I hope this is a good idea :)
    monetaryAmount = _stripCode(currency, monetaryAmountWithIsoCode);
  }

  final decoder = PatternDecoder(currency, pattern);
  final moneyData = decoder.decode(monetaryAmount);

  return Money.fromFixedWithCurrency(moneyData.amount, currency);
}