Skip to content

Commit

Permalink
fix: parse decimals without whole portion (#53)
Browse files Browse the repository at this point in the history
When an transaction entry contains a decimal amount with no whole portion
specified, assume the whole part is zero.
  • Loading branch information
jrick authored Nov 10, 2023
1 parent fa9d808 commit d3041fc
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
15 changes: 11 additions & 4 deletions decimal/decimal.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,16 @@ func atoi64(s string) (bool, int64, error) {
// error if integer parsing fails.
func NewFromString(s string) (Decimal, error) {
if whole, frac, split := strings.Cut(s, "."); split {
neg, w, err := atoi64(whole)
if err != nil {
return Zero, err
var neg bool
var w int64
if whole == "-" {
neg = true
} else if whole != "" {
var err error
neg, w, err = atoi64(whole)
if err != nil {
return Zero, err
}
}

// overflow
Expand Down Expand Up @@ -115,7 +122,7 @@ func NewFromString(s string) (Decimal, error) {
if neg {
f = -f
}
return Decimal(w + f), err
return Decimal(w + f), nil
} else {
_, i, err := atoi64(s)
if i > parseMax || i < parseMin {
Expand Down
10 changes: 10 additions & 0 deletions decimal/decimal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,16 @@ var testParseCases = []testCase{
`atoi failed`,
"(123 * 6)",
},
{
"missingwhole",
"0.50",
".50",
},
{
"negmissingwhole",
"-0.50",
"-.50",
},
}

func TestStringParse(t *testing.T) {
Expand Down

0 comments on commit d3041fc

Please sign in to comment.