money2
Search…
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.
1
final aud = Currency.create('AUD', 2);
Copied!
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:
1
final aud = Currency.create('AUD', 2);
2
final one = aud.parse(r'$1.12345');
3
expect(one.minorUnits.toInt(), equals(112));
Copied!
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.
1
final aud = Currency.create('AUD', 2);
2
final one = aud.parse(r'$1.12345');
3
expect(one.format('#.###'), equals('1.12'));
Copied!
You can however force trailing zeros to be appended by using '0' in your format pattern.
1
final aud = Currency.create('AUD', 2);
2
final one = aud.parse(r'$1.12345');
3
expect(one.format('#.000'), equals('1.120'));
Copied!
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

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.
1
Currency aud4 = CommonCurrencies().aud.copyWith(scale: 4);
2
Currency aud6 = Currency.create('AUD', scale: 4, pattern: '0.0000');
3
Copied!
If you entire application needs to use the high precision version of the AUD you can overwrite the standard CommonCurrency:
1
Currencies.register(CommonCurrencies().aud.copyWith(scale: 5));
2
var aud = Currencies.find('AUD')!.precision == 5;
Copied!
Once you have registered the updated currency any code that references the 'AUD' currency by its code will return your custom currency.