In a recent project, I found it useful to round a %Money{} value for displaying a summary of an amount without any fractional portion. To that end, I've added a basic round/1,2 function that will round the amount in a Money struct. Rounding takes place based on the currency's exponent and will use the rounding mode set in the Decimal context.
The places argument is somewhat awkward, but I chose to pass through the same value used by Decimal instead of manipulating it internally.
Passing 0 for places (the default) will result in rounding off anything below the exponent. For example, Money.round(Money.new(123456, :GBP)) will return %Money{amount: 123500, currency: :GBP}.
Users can pass a negative value to round more significant digits away from the exponent. For example, Money.round(Money.new(-123420, :EUR), -3) will return %Money{amount: -100000, currency: :EUR}. If anyone prefers a different pattern for this argument or has an idea for a clearer API, I'm happy to revisit and change this.
I've also removed the import from Kernel for the global round function, so that we can define our own round within Money.
In a recent project, I found it useful to round a
%Money{}
value for displaying a summary of an amount without any fractional portion. To that end, I've added a basicround/1,2
function that will round theamount
in a Money struct. Rounding takes place based on the currency's exponent and will use the rounding mode set in the Decimal context.This pull request may also address the request for rounding in https://github.com/elixirmoney/money/issues/159.
Notes on the API
The
places
argument is somewhat awkward, but I chose to pass through the same value used byDecimal
instead of manipulating it internally.0
forplaces
(the default) will result in rounding off anything below the exponent. For example,Money.round(Money.new(123456, :GBP))
will return%Money{amount: 123500, currency: :GBP}
.Money.round(Money.new(-123420, :EUR), -3)
will return%Money{amount: -100000, currency: :EUR}
. If anyone prefers a different pattern for this argument or has an idea for a clearer API, I'm happy to revisit and change this.I've also removed the import from Kernel for the global
round
function, so that we can define our ownround
within Money.