Skip to content

Commit 05d3e0b

Browse files
committed
fix: prevent formating issues with decimal
1 parent 3609e94 commit 05d3e0b

3 files changed

Lines changed: 19 additions & 7 deletions

File tree

decimal.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"io"
66
"math"
77
"strconv"
8+
"strings"
89
)
910

1011
const maxDecDigit = 3
@@ -21,18 +22,18 @@ func marshalDecimal(b io.StringWriter, d float64) error {
2122
const TH = 0.001
2223

2324
rounded := math.RoundToEven(d/TH) * TH
24-
i, frac := math.Modf(math.RoundToEven(d/TH) * TH)
25+
i, frac := math.Modf(rounded)
2526

2627
if i < -999999999999 || i > 999999999999 {
2728
return ErrInvalidDecimal
2829
}
2930

30-
if _, err := b.WriteString(strconv.FormatFloat(rounded, 'f', -1, 64)); err != nil {
31+
if _, err := b.WriteString(strings.TrimRight(strconv.FormatFloat(rounded, 'f', 3, 64), "0")); err != nil {
3132
return err
3233
}
3334

3435
if frac == 0 {
35-
_, err := b.WriteString(".0")
36+
_, err := b.WriteString("0")
3637

3738
return err
3839
}

decimal_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ func TestDecimalMarshalSFV(t *testing.T) {
2323
{9999999999999, "", false},
2424
{-9999999999999.0, "", false},
2525
{9999999999999.0, "", false},
26+
{1.9, "1.9", true},
2627
}
2728

2829
var b strings.Builder

list_test.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -120,21 +120,31 @@ func FuzzUnmarshalList(f *testing.F) {
120120
`("é")`,
121121
`(""`,
122122
`(`,
123+
"1.9",
123124
}
124125

125126
for _, t := range testCases {
126127
f.Add(t)
127128
}
128129

129130
f.Fuzz(func(t *testing.T, b string) {
130-
l, err := UnmarshalList([]string{b})
131-
131+
unmarshaled, err := UnmarshalList([]string{b})
132132
if err != nil {
133133
return
134134
}
135135

136-
if _, err := Marshal(l); err != nil {
137-
t.Errorf("Unexpected marshaling error %q for %q, %#v", err, b, l)
136+
reMarshaled, err := Marshal(unmarshaled)
137+
if err != nil {
138+
t.Errorf("Unexpected marshaling error %q for %q, %#v", err, b, unmarshaled)
139+
}
140+
141+
reUnmarshaled, err := UnmarshalList([]string{reMarshaled})
142+
if err != nil {
143+
t.Errorf("Unexpected remarshaling error %q for %q; original %q", err, reMarshaled, b)
144+
}
145+
146+
if !reflect.DeepEqual(unmarshaled, reUnmarshaled) {
147+
t.Errorf("Unmarshaled and re-unmarshaled doesn't match: %#v; %#v", unmarshaled, reUnmarshaled)
138148
}
139149
})
140150
}

0 commit comments

Comments
 (0)