Skip to content

Commit

Permalink
fix(types): positive decimal from string must be finite (#1210)
Browse files Browse the repository at this point in the history
* fix(types): positive decimal from string must be finite

* fix(types): positive decimal from string must be finite

* add godocs and test

* remove miscommit test files

* update test per review comment
  • Loading branch information
ryanchristo authored Jun 28, 2022
1 parent 032340f commit 2800b3c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
10 changes: 9 additions & 1 deletion types/math/dec.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func NewPositiveDecFromString(s string) (Dec, error) {
if err != nil {
return Dec{}, ErrInvalidDecString.Wrap(err.Error())
}
if !d.IsPositive() {
if !d.IsPositive() || !d.IsFinite() {
return Dec{}, ErrInvalidDecString.Wrapf("expected a positive decimal, got %s", s)
}
return d, nil
Expand Down Expand Up @@ -246,18 +246,26 @@ func (x Dec) Equal(y Dec) bool {
return x.dec.Cmp(&y.dec) == 0
}

// IsZero returns true if the decimal is zero.
func (x Dec) IsZero() bool {
return x.dec.IsZero()
}

// IsNegative returns true if the decimal is negative.
func (x Dec) IsNegative() bool {
return x.dec.Negative && !x.dec.IsZero()
}

// IsPositive returns true if the decimal is positive.
func (x Dec) IsPositive() bool {
return !x.dec.Negative && !x.dec.IsZero()
}

// IsFinite returns true if the decimal is finite.
func (x Dec) IsFinite() bool {
return x.dec.Form == apd.Finite
}

// NumDecimalPlaces returns the number of decimal places in x.
func (x Dec) NumDecimalPlaces() uint32 {
exp := x.dec.Exponent
Expand Down
12 changes: 12 additions & 0 deletions types/math/dec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,18 @@ func floatDecimalPlaces(t *rapid.T, f float64) uint32 {
}
}

func TestIsFinite(t *testing.T) {
a, err := NewDecFromString("1.5")
require.NoError(t, err)

require.True(t, a.IsFinite())

b, err := NewDecFromString("NaN")
require.NoError(t, err)

require.False(t, b.IsFinite())
}

func TestReduce(t *testing.T) {
a, err := NewDecFromString("1.30000")
require.NoError(t, err)
Expand Down

0 comments on commit 2800b3c

Please sign in to comment.