Skip to content

fmt: do not remove trailing zeros for %g and %G with #(sharp) flag #36588

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 15 commits into from
Closed
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