Registering a Currency

Money2 ships with a list of Common Currencies however there are times when you may want to add additional currencies (e.g. digital currencies) or change the defaults for an existing Common Currency.

When creating custom Currencies you have two choices, register the currency as a Common Currency, with the benefit that you can access it like any other currency, or create and manage the currency in your own code.

Both methods are useful at different times so use the one that best suits your use case.

import 'package:money2/money2.dart';
import 'package:test/test.dart';

void main() {
  test('register currency', () {
    /// Create currency and replace the CommonCurrency with our
    /// own one.
    Currency usd = Currency.create('USD', 2);
    Currencies().register(usd);

    /// Change the euro common currency to have 4 decimal places
    Currency euro = CommonCurrencies().euro.copyWith(scale: 4);
    Currencies().register(euro);
    expect(CommonCurrencies().euro.scale, equals(4));

    /// register a new currency with 8 decimals.
    final Currency doge =
        Currency.create('DODG', 8, symbol: 'Ð', pattern: 'S0.00000000');
    Currencies().register(doge);

    // find a registered currency.
    Currency? nowUseIt = Currencies().find('DODGE');
    if (nowUseIt != null) {
      Money cost = Money.fromIntWithCurrency(1000000000, nowUseIt);
      expect(cost.toString(), equals(r'Ð10.00000000'));
    }
  });
}

Last updated