Skip to content

Commit d3041fc

Browse files
authored
fix: parse decimals without whole portion (#53)
When an transaction entry contains a decimal amount with no whole portion specified, assume the whole part is zero.
1 parent fa9d808 commit d3041fc

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

decimal/decimal.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,16 @@ func atoi64(s string) (bool, int64, error) {
8282
// error if integer parsing fails.
8383
func NewFromString(s string) (Decimal, error) {
8484
if whole, frac, split := strings.Cut(s, "."); split {
85-
neg, w, err := atoi64(whole)
86-
if err != nil {
87-
return Zero, err
85+
var neg bool
86+
var w int64
87+
if whole == "-" {
88+
neg = true
89+
} else if whole != "" {
90+
var err error
91+
neg, w, err = atoi64(whole)
92+
if err != nil {
93+
return Zero, err
94+
}
8895
}
8996

9097
// overflow
@@ -115,7 +122,7 @@ func NewFromString(s string) (Decimal, error) {
115122
if neg {
116123
f = -f
117124
}
118-
return Decimal(w + f), err
125+
return Decimal(w + f), nil
119126
} else {
120127
_, i, err := atoi64(s)
121128
if i > parseMax || i < parseMin {

decimal/decimal_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,16 @@ var testParseCases = []testCase{
341341
`atoi failed`,
342342
"(123 * 6)",
343343
},
344+
{
345+
"missingwhole",
346+
"0.50",
347+
".50",
348+
},
349+
{
350+
"negmissingwhole",
351+
"-0.50",
352+
"-.50",
353+
},
344354
}
345355

346356
func TestStringParse(t *testing.T) {

0 commit comments

Comments
 (0)