Skip to content

Commit 42b93b7

Browse files
yah01robpike
authored andcommitted
fmt: do not remove trailing zeros for %g and %G with #(sharp) flag
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]>
1 parent 7a03d79 commit 42b93b7

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/fmt/fmt_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,15 @@ var fmtTests = []struct {
463463
{"%#.4x", 1.0, "0x1.0000p+00"},
464464
{"%#.4g", 1.0, "1.000"},
465465
{"%#.4g", 100000.0, "1.000e+05"},
466+
{"%#.4g", 1.234, "1.234"},
467+
{"%#.4g", 0.1234, "0.1234"},
468+
{"%#.4g", 1.23, "1.230"},
469+
{"%#.4g", 0.123, "0.1230"},
470+
{"%#.4g", 1.2, "1.200"},
471+
{"%#.4g", 0.12, "0.1200"},
472+
{"%#.4g", 10.2, "10.20"},
473+
{"%#.4g", 0.0, "0.000"},
474+
{"%#.4g", 0.012, "0.01200"},
466475
{"%#.0f", 123.0, "123."},
467476
{"%#.0e", 123.0, "1.e+02"},
468477
{"%#.0x", 123.0, "0x1.p+07"},

src/fmt/format.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,7 @@ func (f *fmt) fmtFloat(v float64, size int, verb rune, prec int) {
536536
tail := tailBuf[:0]
537537

538538
hasDecimalPoint := false
539+
sawNonzeroDigit := false
539540
// Starting from i = 1 to skip sign at num[0].
540541
for i := 1; i < len(num); i++ {
541542
switch num[i] {
@@ -552,10 +553,20 @@ func (f *fmt) fmtFloat(v float64, size int, verb rune, prec int) {
552553
}
553554
fallthrough
554555
default:
555-
digits--
556+
if num[i] != '0' {
557+
sawNonzeroDigit = true
558+
}
559+
// Count significant digits after the first non-zero digit.
560+
if sawNonzeroDigit {
561+
digits--
562+
}
556563
}
557564
}
558565
if !hasDecimalPoint {
566+
// Leading digit 0 should contribute once to digits.
567+
if len(num) == 2 && num[1] == '0' {
568+
digits--
569+
}
559570
num = append(num, '.')
560571
}
561572
for digits > 0 {

0 commit comments

Comments
 (0)