Money encoding/decoding

API for encoding/decoding a money value enables an application to store values in a database or send over a network.

A money value can be encoded to any type. For example it can be coded as a string in the format like 'USD 5.00'.

Note: this is a trivial example and you would simply use the parse/format methods to encode/decode from/to a string.

Encoding

import 'package:money2/money2.dart';
class MoneyToStringEncoder implements MoneyEncoder<String> {
  String encode(MoneyData data) {
    // Receives MoneyData DTO and produce
    // a string representation of money value...
    String major = data.getMajorUnits().toString();
    String mainor = data.getMinorUnits().toString();

    return data.currency.code + ' ' + major + '.' + minor;
  }
}


final encoded = fiveDollars.encodedBy(MoneyToStringEncoder());
// Now we can save `encoded` to database...

Decoding

import 'package:money2/money2.dart';
class StringToMoneyDecoder implements MoneyDecoder<String> {

  Currencies _currencies;

  StringToMoneyDecoder(this._currencies) {
    if (_currencies == null) {
      throw ArgumentError.notNull('currencies');
    }
  }

  /// Returns decoded `MoneyData` or throws a `FormatException`.
  MoneyData decode(String encoded) {
    // If `encoded` has an invalid format throws FormatException;

    // Extracts currency code from `encoded`:
    final currencyCode = ...;

    // Tries to find information about a currency:
    final currency = _currencies.find(currencyCode);
    if (currency == null) {
      throw FormatException('Unknown currency: $currencyCode.');
    }

    // Using `currency.precision`, extracts minorUnits from `encoded`:
    final minorUnits = ...;

    return MoneyData.from(minorUnits, currency);
  }
}
import 'money2.dart';
try {
  final value = Money.decoding('USD 5.00', MyMoneyDecoder(myCurrencies));

  // ...
} on FormatException {
  // ...
}

Last updated