Skip to content

Commit 74f914a

Browse files
randall77pull[bot]
authored andcommitted
cmd/compile: in compiler errors, print more digits for floats close to an int
Error messages currently print floats with %.6g, which means that if you tried to convert something close to, but not quite, an integer, to an integer, the error you get looks like "cannot convert 1 to type int", when really you want "cannot convert 0.9999999 to type int". Add more digits to floats when printing them, to make it clear that they aren't quite integers. This helps for errors which are the result of not being an integer. For other errors, it won't hurt much. Fixes #56220 Change-Id: I7f5873af5993114a61460ef399d15316925a15a5 Reviewed-on: https://go-review.googlesource.com/c/go/+/442935 Reviewed-by: Rob Pike <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Robert Griesemer <[email protected]> Reviewed-by: Keith Randall <[email protected]> Run-TryBot: Keith Randall <[email protected]>
1 parent 66b1b74 commit 74f914a

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/go/constant/value.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,13 @@ func (x floatVal) String() string {
200200
// Use exact fmt formatting if in float64 range (common case):
201201
// proceed if f doesn't underflow to 0 or overflow to inf.
202202
if x, _ := f.Float64(); f.Sign() == 0 == (x == 0) && !math.IsInf(x, 0) {
203-
return fmt.Sprintf("%.6g", x)
203+
s := fmt.Sprintf("%.6g", x)
204+
if !f.IsInt() && strings.IndexByte(s, '.') < 0 {
205+
// f is not an integer, but its string representation
206+
// doesn't reflect that. Use more digits. See issue 56220.
207+
s = fmt.Sprintf("%g", x)
208+
}
209+
return s
204210
}
205211

206212
// Out of float64 range. Do approximate manual to decimal

test/fixedbugs/issue56220.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// errorcheck
2+
3+
// Copyright 2022 The Go Authors. All rights reserved.
4+
// Use of this source code is governed by a BSD-style
5+
// license that can be found in the LICENSE file.
6+
7+
package p
8+
9+
func f() int {
10+
return int(1 - .0000001) // ERROR "cannot convert 1 - \.0000001 \(untyped float constant 0\.9999999\) to type int"
11+
}
12+
13+
func g() int64 {
14+
return int64((float64(0.03) - float64(0.02)) * 1_000_000) // ERROR "cannot convert \(float64\(0\.03\) - float64\(0\.02\)\) \* 1_000_000 \(constant 9999\.999999999998 of type float64\) to type int64"
15+
}

0 commit comments

Comments
 (0)