Reputation: 315
In my project I have to calculate a total price of a product by multiplying a price in Decimal to quantity in Integer. When I do so, I'm getting an exception "bad argument in arithmetic expression". How can solve that? I wouldn't want to lose data if I have to round
a result.
Upvotes: 3
Views: 2642
Reputation: 222348
Elixir does not allow operator overloading, so the decimal
package cannot make the *
operator work on Decimal
. The package does provide a function Decimal.mult/2
to multiply Decimal
values, which accepts 2 Decimal
values, which you can use. You need to first convert the integer to a Decimal
using Decimal.new/1
and then use Decimal.mult/2
:
iex(1)> d = Decimal.new("0.11111111111111111111")
#Decimal<0.11111111111111111111>
iex(2)> Decimal.mult(d, Decimal.new(3))
#Decimal<0.33333333333333333333>
iex(3)> 0.11111111111111111111 * 3 # This loses precision because Elixir's native floats are 64 bit IEEE floats
0.3333333333333333
Upvotes: 8