ericmj / decimal

Arbitrary precision decimal arithmetic

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Decimal.new/3 allows negative coefficient values

hackmad opened this issue · comments

We found a recent bug when working with xandra and their decimal conversion. I believe this is because Decimal.new/3 is not guarding against negative coefficients. This is in v1.7.0.

iex(14)> dec = Decimal.new(-1, -500, -2)
#Decimal<--5.00>
iex(15)> Decimal.positive?(dec)         
false
iex(16)> Decimal.negative?(dec)         
true
iex(17)> Decimal.add(dec, 0)   
#Decimal<5.00>

Thanks for finding and reporting the issue. I will fix this in master.

I just checked the update but it prevents you from doing this:

iex(8)> Decimal.new(1, 0, 0)
** (FunctionClauseError) no function clause matching in Decimal.new/3

    The following arguments were given to Decimal.new/3:

        # 1
        1

        # 2
        0

        # 3
        0

    Attempted function clauses (showing 1 out of 1):

        def new(sign, coef, exp) when (sign === -1 or sign === 1) and (is_integer(coef) and coef > 0 or (coef === :sNan or (coef === :inf or coef === :qNaN))) and is_integer(exp)

    (decimal) lib/decimal.ex:1263: Decimal.new/3

So there is no way to create zero with this. It is inconsistent with this:

iex(12)> %Decimal{coef: coef, sign: sign, exp: exp} = Decimal.new(0)
#Decimal<0>
iex(13)> "coef = #{coef}, sign = #{sign}, exp =  #{exp}"
"coef = 0, sign = 1, exp =  0"

Thanks, should also be fixed now.

Thanks. Will you be doing a release with these changes?

Release is pushed.