Skip to content

Commit

Permalink
More defensive check for Go fmt float whole-number bug
Browse files Browse the repository at this point in the history
  • Loading branch information
dave committed Jul 13, 2018
1 parent 1f18369 commit 1e7350a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
5 changes: 5 additions & 0 deletions jen/jen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ var o2 = Options{
}

var cases = []tc{
{
desc: `lit float whole numbers`,
code: Index().Float64().Values(Lit(-3.0), Lit(-2.0), Lit(-1.0), Lit(0.0), Lit(1.0), Lit(2.0), Lit(3.0)),
expect: "[]float64{-3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0}",
},
{
desc: `custom func group`,
code: ListFunc(func(g *Group) {
Expand Down
11 changes: 8 additions & 3 deletions jen/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,14 @@ func (t token) render(f *File, w io.Writer, s *Statement) error {
// default constant types can be left bare
out = fmt.Sprintf("%#v", t.content)
case float64:
// float is a special case because fmt package doesn't format correctly
if v == float64(int64(v)) {
// float is a special case because fmt package doesn't format correctly. We check that the
// bug still exists to gracefully handle the possibility that a future Go release will fix
// this bug. See:
// https://github.com/dave/jennifer/issues/39
// https://github.com/golang/go/issues/26363
if v == float64(int64(v)) && fmtBugStillExists {
// value is a whole number, so fmt package will omit the
// trailing ".0", so we add it.
// TODO: More testing needed for this. Corner cases?
out = fmt.Sprintf("%#v.0", t.content)
} else {
out = fmt.Sprintf("%#v", t.content)
Expand Down Expand Up @@ -298,3 +301,5 @@ func (s *Statement) Line() *Statement {
*s = append(*s, t)
return s
}

var fmtBugStillExists = fmt.Sprintf("%#v", 1.0) == "1"

0 comments on commit 1e7350a

Please sign in to comment.