Scale

When defining a Currency you must define the number of digits after the decimal place that will be stored. This is referred to as the Scale of the currency.

final aud = Currency.create('AUD', 2);

In the above example we create a Currency for the Australian Dollar with a scale of 2.

The stored scale will affect all calculations performed on Money objects created for the Currency in that all calculations will be rounded to the defined scale.

Parsing

When we parse a monetary amount the Currencies scale affects how the amount is parsed.

If we parse an AUD amount it will always be stored with 2 decimals regardless of the value we passed:

final aud = Currency.create('AUD', 2);
final one = aud.parse(r'$1.12345');
expect(one.minorUnits.toInt(), equals(112));

As you can see, even though we parsed 5 decimal places we only stored 2 decimal places as the currency has a scale of two.

Formatting

The scale also affects formatting. As the monetary amount is always rounded to the scale you can't print more decimal places than the amount retrains.

final aud = Currency.create('AUD', 2);
final one = aud.parse(r'$1.12345');
expect(one.format('#.###'), equals('1.12'));

You can however force trailing zeros to be appended by using '0' in your format pattern.

final aud = Currency.create('AUD', 2);
final one = aud.parse(r'$1.12345');
expect(one.format('#.000'), equals('1.120'));

In practice it is recommended that you only use the '0' pattern character for decimal places so you always output a consistent no. of decimals.

Customising the Scale

Note: Money2 has a maximum scale of 18 decimal places.

Money ships with a collection of CommonCurrencies. Each of the common currencies has a precision that conforms to the currencies standard scale. e.g. The USD has a scale of 2.

If you need to use a non-standard scale for a Currency then you will need to create your own currency object rather than relying on one of the CommonCurrencies or copy one of the common currencies.

Currency aud4 = CommonCurrencies().aud.copyWith(scale: 4);
Currency aud6 = Currency.create('AUD', scale: 4, pattern: '0.0000');

If you entire application needs to use the high precision version of the AUD you can overwrite the standard CommonCurrency:

Currencies.register(CommonCurrencies().aud.copyWith(scale: 5));
var aud = Currencies.find('AUD')!.precision == 5;

Once you have registered the updated currency any code that references the 'AUD' currency by its code will return your custom currency.

Last updated