ericmj / decimal

Arbitrary precision decimal arithmetic

Home Page:https://hexdocs.pm/decimal/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to catch invalid numbers?

intentionally-left-nil opened this issue · comments

I have user input that may or may not be a number. How can I use the Decimal library to determine this? I'm seemingly unable to catch the Decimal.Error

defmodule Test do
  def bad_number() do
    try do
      Decimal.new("not a number")
    catch
      e -> IO.puts("This never gets called: #{inspect(e)}" )
    end
  end
end

results in:

iex(4)> Test.bad_number()
** (Decimal.Error) : number parsing syntax: "not a number"
    (decimal 2.0.0) lib/decimal.ex:1094: Decimal.new/1
    iex:6: Test.bad_number/0
    iex:4: (file)

It must be too early in the morning. I need rescue of coruse :(

Btw, instead of rescuing exceptions you have two additional options that return ok/error tuples:

  1. if you're accepting just strings, use Decimal.parse/1.
  2. otherwise, you can use Decimal.cast/1.