I am implementing an application that deals with monetary values. Therefore I use the excellent Decimal library to handle such values.
Now arithmetic is supported by the various functions provided by the module, e.g.
But this results in very hard to read and write code, take this for an example:
# I would love to write: distance = price / order_price # But I have to write: distance = Decimal.div(price, order_price) # This gets even more messy when dealing with multiple values multiplier = 0.2 sale = Decimal.add(price, Decimal.mult(price, Decimal.new(multiplier)))
defmacro to the rescue?
Yea, I thought I really have a clean solution with a prefix macro that deals with decimal arithmetic.
Now, in my tests writing this prefix-macro I could do this:
a = Decimal.new(1) b = Decimal.new(2) result = decimal a + b assert result == Decimal.new(3) # Tests passed, hooray!
But as soon as I used this code in my application, suddenly I got lots of
(ArithmeticError) bad argument in arithmetic expression
Why is this happening? Is Elixir inlining the arithmetic expressions and therefore falling back to the Kernel defaults?
I thought I explicitly loaded the
Decimal.Prefix macros in the
The weird thing, tests pass just fine, but I don’t get why errors appear when the application runs.
And I double checked the inputs, they are all of
Help in this matter (also the original thing, dealing with monetary values doing arithmetic with these) is highly appreciated.