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
This commit is contained in:
Thomas Pelletier
2017-06-01 21:36:58 -07:00
committed by GitHub
parent a60c71373e
commit 0d5a6db8dd
2 changed files with 21 additions and 0 deletions
+6
View File
@@ -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
+15
View File
@@ -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 {