ericmj / decimal

Arbitrary precision decimal arithmetic

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Raise nicer error from Decimal.to_integer

wojtekmach opened this issue · comments

iex> Decimal.new("1.1") |> Decimal.to_integer
** (FunctionClauseError) no function clause matching in Decimal.to_integer/1

    The following arguments were given to Decimal.to_integer/1:

        # 1
        #Decimal<1.1>

    Attempted function clauses (showing 3 out of 3):

        def to_integer(%Decimal{sign: sign, coef: coef, exp: 0})         when is_integer(coef)
        def to_integer(%Decimal{sign: sign, coef: coef, exp: exp})         when is_integer(coef) and exp > 0
        def to_integer(%Decimal{sign: sign, coef: coef, exp: exp})         when is_integer(coef) and exp < 0 and rem(coef, 10) == 0

    (decimal 2.0.0) lib/decimal.ex:1322: Decimal.to_integer/1

The same - why does it get raised at all? What's wrong?

iex(2)> a1 = Decimal.new("106.5")
#Decimal<106.5>

iex(3)> Decimal.to_integer a1
** (FunctionClauseError) no function clause matching in Decimal.to_integer/1    
    
    The following arguments were given to Decimal.to_integer/1:
    
        # 1
        #Decimal<106.5>
    
    Attempted function clauses (showing 3 out of 3):
    
        def to_integer(%Decimal{sign: sign, coef: coef, exp: 0}) when is_integer(coef)
        def to_integer(%Decimal{sign: sign, coef: coef, exp: exp}) when is_integer(coef) and exp > 0
        def to_integer(%Decimal{sign: sign, coef: coef, exp: exp}) when is_integer(coef) and exp < 0 and rem(coef, 10) == 0
    
    (decimal 2.0.0) lib/decimal.ex:1322: Decimal.to_integer/1

It used to work. How to fix it?

We cannot do this conversion because we’d lose precision and the error message should say as much

Oh and to answer your question, we can fix it like this: d |> Decimal.round |> Decimal.to_integer