tpl: Fix bad rounding in NumFmt
authorSam Smith <sams96@mail.com>
Wed, 1 Apr 2020 22:13:23 +0000 (23:13 +0100)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Tue, 2 Jun 2020 15:20:36 +0000 (17:20 +0200)
strconv.FormatFloat doesn't round properly sometimes, this adds a
different method of rounding, fixes #7116

tpl/lang/lang.go
tpl/lang/lang_test.go

index 9a9f467bbc399078378ea603fded2540eabde582..491e2492e001dce04e0d8e3f1d3ba684992bc97f 100644 (file)
@@ -102,10 +102,13 @@ func (ns *Namespace) NumFmt(precision, number interface{}, options ...interface{
                }
        }
 
+       exp := math.Pow(10.0, float64(prec))
+       r := math.Round(n*exp) / exp
+
        // Logic from MIT Licensed github.com/go-playground/locales/
        // Original Copyright (c) 2016 Go Playground
 
-       s := strconv.FormatFloat(math.Abs(n), 'f', prec, 64)
+       s := strconv.FormatFloat(math.Abs(r), 'f', prec, 64)
        L := len(s) + 2 + len(s[:len(s)-1-prec])/3
 
        var count int
index e62faf2ac98ab6ebb6c8cb85f5a423217e664176..3b3caeb625472c1cd23649144b48654992823c3c 100644 (file)
@@ -29,6 +29,10 @@ func TestNumFormat(t *testing.T) {
                {0, 12345.6789, "- . ,", "", "12,346"},
                {11, -12345.6789, "- . ,", "", "-12,345.67890000000"},
 
+               {2, 927.675, "- .", "", "927.68"},
+               {2, 1927.675, "- .", "", "1927.68"},
+               {2, 2927.675, "- .", "", "2927.68"},
+
                {3, -12345.6789, "- ,", "", "-12345,679"},
                {6, -12345.6789, "- , .", "", "-12.345,678900"},