decimalDigits
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 decimalDigits (or more technically scale) of the currency.
In the above example we create a Currency for the Australian Dollar with 2 decimal digits.
The defined number of decimal digits will affect all calculations performed on Money objects created for the Currency in that all calculations will be rounded to the defined number of decimal digits.
Parsing
When we parse a monetary amount the Currencies number of decimal digits 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:
As you can see, even though we parsed 5 decimal places we only stored 2 decimal places as the currency is defined as storing 2 decimal digits.
Formatting
The number of decimal digits also affects formatting. As the monetary amount is always rounded to the number of decimal digits you can't print more decimal places than the amount retrains.
You can however force trailing zeros to be appended by using '0' in your format pattern.
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 number of Decimal Digits
Note: Money2 is tested with up to 100 decimal digits but should work with a higher precisions as we store the amount as a BigInt which is only limited by memory.
Money ships with a collection of CommonCurrencies. Each of the common currencies has a precision that conforms to the currencies standard number of decimal digits. e.g. The USD has 2 decimal digits.
If you need to use a non-standard number of decimals 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.
If you entire application needs to use the high precision version of the AUD you can overwrite the standard CommonCurrency:
Once you have registered the updated currency any code that references the 'AUD' currency by its code will return your custom currency.
Last updated
Was this helpful?