Skip to content

Commit

Permalink
fmt: do not remove trailing zeros for %g and %G with #(sharp) flag
Browse files Browse the repository at this point in the history
Fixes #36562

Change-Id: Id98ae9f7362cfb825b306c36649d505692d6d60e
GitHub-Last-Rev: 405d51b
GitHub-Pull-Request: #36588
Reviewed-on: https://go-review.googlesource.com/c/go/+/215001
Reviewed-by: Rob Pike <[email protected]>
  • Loading branch information
yah01 authored and robpike committed Feb 26, 2020
1 parent 7a03d79 commit 42b93b7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/fmt/fmt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand Down
13 changes: 12 additions & 1 deletion src/fmt/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -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] {
Expand All @@ -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 {
Expand Down

0 comments on commit 42b93b7

Please sign in to comment.