diff options
author | yah01 <kagaminehuan@gmail.com> | 2020-02-26 08:17:14 +0000 |
---|---|---|
committer | Rob Pike <r@golang.org> | 2020-02-26 08:43:57 +0000 |
commit | 42b93b7fe616b685e9ea41514b15bc9c26d3eac8 (patch) | |
tree | 322fac6c4096ebd18c9ef62da0b21259f3a3dd0f /src/fmt | |
parent | 7a03d79498a32eb099d6f82aa8b19e813630be65 (diff) | |
download | go-42b93b7fe616b685e9ea41514b15bc9c26d3eac8.tar.gz go-42b93b7fe616b685e9ea41514b15bc9c26d3eac8.zip |
fmt: do not remove trailing zeros for %g and %G with #(sharp) flag
Fixes #36562
Change-Id: Id98ae9f7362cfb825b306c36649d505692d6d60e
GitHub-Last-Rev: 405d51b12eb04da8cc3559c92f1546e69a8c1a19
GitHub-Pull-Request: golang/go#36588
Reviewed-on: https://go-review.googlesource.com/c/go/+/215001
Reviewed-by: Rob Pike <r@golang.org>
Diffstat (limited to 'src/fmt')
-rw-r--r-- | src/fmt/fmt_test.go | 9 | ||||
-rw-r--r-- | src/fmt/format.go | 13 |
2 files changed, 21 insertions, 1 deletions
diff --git a/src/fmt/fmt_test.go b/src/fmt/fmt_test.go index 072fc6bf3b..6004061020 100644 --- a/src/fmt/fmt_test.go +++ b/src/fmt/fmt_test.go @@ -463,6 +463,15 @@ var fmtTests = []struct { {"%#.4x", 1.0, "0x1.0000p+00"}, {"%#.4g", 1.0, "1.000"}, {"%#.4g", 100000.0, "1.000e+05"}, + {"%#.4g", 1.234, "1.234"}, + {"%#.4g", 0.1234, "0.1234"}, + {"%#.4g", 1.23, "1.230"}, + {"%#.4g", 0.123, "0.1230"}, + {"%#.4g", 1.2, "1.200"}, + {"%#.4g", 0.12, "0.1200"}, + {"%#.4g", 10.2, "10.20"}, + {"%#.4g", 0.0, "0.000"}, + {"%#.4g", 0.012, "0.01200"}, {"%#.0f", 123.0, "123."}, {"%#.0e", 123.0, "1.e+02"}, {"%#.0x", 123.0, "0x1.p+07"}, diff --git a/src/fmt/format.go b/src/fmt/format.go index 74e600cab2..4d12f82f7d 100644 --- a/src/fmt/format.go +++ b/src/fmt/format.go @@ -536,6 +536,7 @@ func (f *fmt) fmtFloat(v float64, size int, verb rune, prec int) { tail := tailBuf[:0] hasDecimalPoint := false + sawNonzeroDigit := false // Starting from i = 1 to skip sign at num[0]. for i := 1; i < len(num); i++ { switch num[i] { @@ -552,10 +553,20 @@ func (f *fmt) fmtFloat(v float64, size int, verb rune, prec int) { } fallthrough default: - digits-- + if num[i] != '0' { + sawNonzeroDigit = true + } + // Count significant digits after the first non-zero digit. + if sawNonzeroDigit { + digits-- + } } } if !hasDecimalPoint { + // Leading digit 0 should contribute once to digits. + if len(num) == 2 && num[1] == '0' { + digits-- + } num = append(num, '.') } for digits > 0 { |