Hello everybody,
In order to deal with currencies, we are used to consider the amounts as cents and then using integers.
One can also simply use the Decimal type which will avoid rounding errors of floats.
Another solution can be to use a package that deal with the currency problem.
In elixir there is two main package: money
and ex_money
But I have a question that always intrigued me… And it’s somehow introduced in the 6th falsehood that is documented in this list (from the ex_money
doc):
Prices can’t have more precision than the smaller sub-unit of the currency. (counter-example: gas prices)
Indeed, while we are ultimately dealing with at least the cent in our day to day life, we can however face smaller amounts, like tenth of cents in gas prices or some fees (like sending a message that can cost 0.001$)
Let’s take that last example…
If I have to send an email every day, I expect to pay 3 cents at the end of the month (considering 30 days).
But what if I’m using a cumulative value?
The first day, the amount will still be 0 in cents (using an integer)., right?
So if I had to sum each day fee, I’ll never be able to sum the whole charge.
How those kind of little amounts are actually handled?
Edit: I noticed that the money
package is using the integer
type for the amount part, while ex_money
is using a decimal
type (to be exact it’s a numeric
type in Postgres, but I guess it’s the same).
Does it mean that with ex_money
I can store an amount like $0.001 while displaying $0, and still having the correct amount stored in the system?
I mean on day 2 the value will be correctly stored as $0.002 but still displayed $0…
Until the day 10 when the value stored will be $0.010 and hence correctly displayed as $0.01.
Did I correctly understand how the Decimal-like type will behave in ex_money
?