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:
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"math"
|
||||||
"reflect"
|
"reflect"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -50,6 +51,11 @@ func tomlValueStringRepresentation(v interface{}) (string, error) {
|
|||||||
case int64:
|
case int64:
|
||||||
return strconv.FormatInt(value, 10), nil
|
return strconv.FormatInt(value, 10), nil
|
||||||
case float64:
|
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
|
return strconv.FormatFloat(value, 'f', -1, 32), nil
|
||||||
case string:
|
case string:
|
||||||
return "\"" + encodeTomlString(value) + "\"", nil
|
return "\"" + encodeTomlString(value) + "\"", nil
|
||||||
|
|||||||
@@ -294,6 +294,21 @@ func TestTreeWriteToMapWithArrayOfInlineTables(t *testing.T) {
|
|||||||
testMaps(t, treeMap, expected)
|
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) {
|
func BenchmarkTreeToTomlString(b *testing.B) {
|
||||||
toml, err := Load(sampleHard)
|
toml, err := Load(sampleHard)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
Reference in New Issue
Block a user