Skip to content

Commit

Permalink
fix: UnmarshalJSON fixed for values without '.'
Browse files Browse the repository at this point in the history
  • Loading branch information
trakhimenok committed May 6, 2024
1 parent 743b998 commit 82fe66a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
19 changes: 14 additions & 5 deletions decimal64p2.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package decimal
import (
"encoding/json"
"math"
"slices"
"strconv"
"strings"
)
Expand Down Expand Up @@ -117,13 +118,21 @@ func (d Decimal64p2) MarshalJSON() ([]byte, error) {
return []byte(d.String()), nil
}

// UnmarshalJSON unmarshals JSON to decimal
// UnmarshalJSON deserializes JSON to decimal
func (d *Decimal64p2) UnmarshalJSON(data []byte) error {
var f float64
if err := json.Unmarshal(data, &f); err != nil {
return err
if slices.Contains(data, '.') {
var f float64
if err := json.Unmarshal(data, &f); err != nil {
return err
}
*d = NewDecimal64p2FromFloat64(f)
} else {
var f int64
if err := json.Unmarshal(data, &f); err != nil {
return err
}
*d = Decimal64p2(f)
}
*d = NewDecimal64p2FromFloat64(f)
return nil
}

Expand Down
11 changes: 10 additions & 1 deletion decimal64p2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ func TestParseDecimal64p2(t *testing.T) {
t.Error(err)
} else if d != 0 {
t.Errorf("Expected 0, got: %v", d)
} else if d.String() != "0" {
} else if //goland:noinspection GoDfaNilDereference
d.String() != "0" {
t.Errorf("Expected 0, got: %v", d.String())
}

Expand Down Expand Up @@ -211,6 +212,14 @@ func TestDecimal64p2_MarshalJSON(t *testing.T) {
func TestDecimal64p2_UnmarshalJSON(t *testing.T) {
var d2 Decimal64p2

if err := json.Unmarshal([]byte("1234"), &d2); err != nil {
t.Error(err)
} else if intPart := d2.IntPart(); intPart != 12 {
t.Errorf("Expected 12 for int part, got %d: %s", intPart, d2.String())
} else if decimalPart := d2.DecimalPart(); decimalPart != 34 {
t.Errorf("Expected 0 for decimal part, got %d: %s", decimalPart, d2.String())
}

if err := json.Unmarshal([]byte("1.23"), &d2); err != nil {
t.Error(err)
} else if d2.IntPart() != 1 || d2.DecimalPart() != 23 {
Expand Down

0 comments on commit 82fe66a

Please sign in to comment.