Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 6 commits into from
Jun 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 {
ryanchristo marked this conversation as resolved.
Show resolved Hide resolved
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