From 0d5a6db8dd354cc13a2838db22be7dfd87e4d9ca Mon Sep 17 00:00:00 2001 From: Thomas Pelletier Date: Thu, 1 Jun 2017 21:36:58 -0700 Subject: [PATCH] Fix toString float encoding (#172) Ensure a round float does contain a decimal point. Otherwise feeding the output back to the parser would convert to an integer. Fixes #171 --- tomltree_write.go | 6 ++++++ tomltree_write_test.go | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/tomltree_write.go b/tomltree_write.go index 836a8de..cd03f9d 100644 --- a/tomltree_write.go +++ b/tomltree_write.go @@ -4,6 +4,7 @@ import ( "bytes" "fmt" "io" + "math" "reflect" "sort" "strconv" @@ -50,6 +51,11 @@ func tomlValueStringRepresentation(v interface{}) (string, error) { case int64: return strconv.FormatInt(value, 10), nil case float64: + // Ensure a round float does contain a decimal point. Otherwise feeding + // the output back to the parser would convert to an integer. + if math.Trunc(value) == value { + return strconv.FormatFloat(value, 'f', 1, 32), nil + } return strconv.FormatFloat(value, 'f', -1, 32), nil case string: return "\"" + encodeTomlString(value) + "\"", nil diff --git a/tomltree_write_test.go b/tomltree_write_test.go index 53e7aa9..0edf1be 100644 --- a/tomltree_write_test.go +++ b/tomltree_write_test.go @@ -294,6 +294,21 @@ func TestTreeWriteToMapWithArrayOfInlineTables(t *testing.T) { testMaps(t, treeMap, expected) } +func TestTreeWriteToFloat(t *testing.T) { + tree, err := Load(`a = 3.0`) + if err != nil { + t.Fatal(err) + } + str, err := tree.ToTomlString() + if err != nil { + t.Fatal(err) + } + expected := `a = 3.0` + if strings.TrimSpace(str) != strings.TrimSpace(expected) { + t.Fatalf("Expected:\n%s\nGot:\n%s", expected, str) + } +} + func BenchmarkTreeToTomlString(b *testing.B) { toml, err := Load(sampleHard) if err != nil {