henriquesati
Decimal not returning a number
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)
Most Liked
cmkarlsson
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 v3.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.
jswanner
DecimalEnv can make it less verbose to deal with decimal arithmetic
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #code-sync
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








