I’m passing a string to decimal.new() and instead of a float it’s returning some data type that not allows me to do aritmetic expressions
def get_USD_amount_basedOn_BRL(brl_amount) do
{_status_code, brl_usd_price_str} = get_brl_usd()
brl_usd_price = Decimal.new(brl_usd_price_str)
IO.inspect(brl_usd_price)
end
end
output expected:
5.65
output received:
Decimal.new("5.5936")
error received when I try to execut arithmetic expressions
** (ArithmeticError) bad argument in arithmetic expression
(testes_pay 0.1.0) lib/UsdBrl.ex:24: UsdBrl.get_USD_amount_basedOn_BRL/1
lib/main.ex:25: (file)
Decimal.new/1
returns a Decimal
struct. You need to use the Decimal
module to do arithmetic operations.
iex(3)> d1 = Decimal.new("5.5623")
Decimal.new("5.5623")
iex(4)> d2 = Decimal.new("3.12")
Decimal.new("3.12")
iex(5)> Decimal.mult(d1, d2)
Decimal.new("17.354376")
iex(6)> Decimal.mult(d1, d2) |> Decimal.round(3)
Decimal.new("17.354")
iex(7)> Decimal.mult(d1, d2) |> Decimal.round(3) |> Decimal.to_float
17.354
Using the decimal for calculations is strongly recommended as using floats is not precise(Floating-point arithmetic - Wikipedia) and can lead to thing like this:
iex(9)> 0.1 + 0.2
0.30000000000000004
# Instead use Decimal
iex(10)> Decimal.add(Decimal.from_float(0.1), Decimal.from_float(0.2)) |> Decimal.to_float
0.3
Check Decimal — Decimal v2.1.1 for more information.
In addition if you are working with money you might want to check out: ex_money | Hex. It is very comprehensive but may be overkill for your situation.
2 Likes
Thanks! and it is possible to turn the final data after all the operations into a normal decimal number?
Yes. The Decimal
module has got functions to convert the result into integers, floats and strings. Often you don’t have to convert it back to a float or other numbers but just to strings for the presentation layer.
EDIT: Some exampels
iex(11)> Decimal.to_string(d1)
"5.5623"
iex(12)> Decimal.to_float(d1)
5.5623
iex(13)> Decimal.round(d1, 0) |> Decimal.to_integer
6
DecimalEnv can make it less verbose to deal with decimal arithmetic
2 Likes