Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/gohugoio/hugo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
path: root/tpl
diff options
context:
space:
mode:
authorSam Smith <sams96@mail.com>2020-04-02 01:13:23 +0300
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>2020-06-02 18:20:36 +0300
commit3d9235e8fcf31553c0c0f313d3264f12438749ea (patch)
treed7cd000a5dd9fbe966b3cbc44434426ba4c27bf9 /tpl
parentf7d909f3948ca3d1318e5b0d6c80d905fc37aea2 (diff)
tpl: Fix bad rounding in NumFmt
strconv.FormatFloat doesn't round properly sometimes, this adds a different method of rounding, fixes #7116
Diffstat (limited to 'tpl')
-rw-r--r--tpl/lang/lang.go5
-rw-r--r--tpl/lang/lang_test.go4
2 files changed, 8 insertions, 1 deletions
diff --git a/tpl/lang/lang.go b/tpl/lang/lang.go
index 9a9f467bb..491e2492e 100644
--- a/tpl/lang/lang.go
+++ b/tpl/lang/lang.go
@@ -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
diff --git a/tpl/lang/lang_test.go b/tpl/lang/lang_test.go
index e62faf2ac..3b3caeb62 100644
--- a/tpl/lang/lang_test.go
+++ b/tpl/lang/lang_test.go
@@ -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"},