Skip to content

Commit 888fe5c

Browse files
leelynneLeedunglas
authored
fix: decimal formatting issues (#14)
* Fix decimal formatting issues and test. The 'frac' component won't always be zero due to floating point but strconv.FormatFloat will round to 3 places and can output a whole number. Checking for a decimal at the end is more reliable to detect the rounding * fix: use strings.HasSuffix for clarity --------- Co-authored-by: Lee <lee@ip-192-168-193-193.us-west-2.compute.internal> Co-authored-by: Kévin Dunglas <kevin@dunglas.dev>
1 parent 4cd96ca commit 888fe5c

1 file changed

Lines changed: 7 additions & 9 deletions

File tree

decimal.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,21 @@ func marshalDecimal(b io.StringWriter, d float64) error {
2222
const TH = 0.001
2323

2424
rounded := math.RoundToEven(d/TH) * TH
25-
i, frac := math.Modf(rounded)
25+
i, _ := math.Modf(rounded)
2626

2727
if i < -999999999999 || i > 999999999999 {
2828
return ErrInvalidDecimal
2929
}
3030

31-
if _, err := b.WriteString(strings.TrimRight(strconv.FormatFloat(rounded, 'f', 3, 64), "0")); err != nil {
32-
return err
31+
s := strings.TrimRight(strconv.FormatFloat(rounded, 'f', 3, 64), "0")
32+
// Ensure at least one digit after the decimal point.
33+
if strings.HasSuffix(s, ".") {
34+
s += "0"
3335
}
3436

35-
if frac == 0 {
36-
_, err := b.WriteString("0")
37+
_, err := b.WriteString(s)
3738

38-
return err
39-
}
40-
41-
return nil
39+
return err
4240
}
4341

4442
func parseDecimal(s *scanner, decSepOff int, str string, neg bool) (float64, error) {

0 commit comments

Comments
 (0)