From 42b93b7fe616b685e9ea41514b15bc9c26d3eac8 Mon Sep 17 00:00:00 2001 From: yah01 Date: Wed, 26 Feb 2020 08:17:14 +0000 Subject: [PATCH] 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 --- src/fmt/fmt_test.go | 9 +++++++++ src/fmt/format.go | 13 ++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/fmt/fmt_test.go b/src/fmt/fmt_test.go index 072fc6bf3b4..60040610205 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 74e600cab26..4d12f82f7de 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 {