encode: ensure floats have decimal point (#615)
Fixes #571 Co-authored-by: Sterling Hanenkamp <sterling@ziprecruiter.com>
This commit is contained in:
committed by
GitHub
parent
86632bc190
commit
4984dcb5e9
@@ -5,6 +5,7 @@ import (
|
|||||||
"encoding"
|
"encoding"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"math"
|
||||||
"reflect"
|
"reflect"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -244,9 +245,17 @@ func (enc *Encoder) encode(b []byte, ctx encoderCtx, v reflect.Value) ([]byte, e
|
|||||||
case reflect.String:
|
case reflect.String:
|
||||||
b = enc.encodeString(b, v.String(), ctx.options)
|
b = enc.encodeString(b, v.String(), ctx.options)
|
||||||
case reflect.Float32:
|
case reflect.Float32:
|
||||||
|
if math.Trunc(v.Float()) == v.Float() {
|
||||||
|
b = strconv.AppendFloat(b, v.Float(), 'f', 1, 32)
|
||||||
|
} else {
|
||||||
b = strconv.AppendFloat(b, v.Float(), 'f', -1, 32)
|
b = strconv.AppendFloat(b, v.Float(), 'f', -1, 32)
|
||||||
|
}
|
||||||
case reflect.Float64:
|
case reflect.Float64:
|
||||||
|
if math.Trunc(v.Float()) == v.Float() {
|
||||||
|
b = strconv.AppendFloat(b, v.Float(), 'f', 1, 64)
|
||||||
|
} else {
|
||||||
b = strconv.AppendFloat(b, v.Float(), 'f', -1, 64)
|
b = strconv.AppendFloat(b, v.Float(), 'f', -1, 64)
|
||||||
|
}
|
||||||
case reflect.Bool:
|
case reflect.Bool:
|
||||||
if v.Bool() {
|
if v.Bool() {
|
||||||
b = append(b, "true"...)
|
b = append(b, "true"...)
|
||||||
|
|||||||
@@ -822,3 +822,26 @@ func ExampleMarshal() {
|
|||||||
// Name = 'go-toml'
|
// Name = 'go-toml'
|
||||||
// Tags = ['go', 'toml']
|
// Tags = ['go', 'toml']
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIssue571(t *testing.T) {
|
||||||
|
type Foo struct {
|
||||||
|
Float32 float32
|
||||||
|
Float64 float64
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeEnough = 1e-9
|
||||||
|
|
||||||
|
foo := Foo{
|
||||||
|
Float32: 42,
|
||||||
|
Float64: 43,
|
||||||
|
}
|
||||||
|
b, err := toml.Marshal(foo)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
var foo2 Foo
|
||||||
|
err = toml.Unmarshal(b, &foo2)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
assert.InDelta(t, 42, foo2.Float32, closeEnough)
|
||||||
|
assert.InDelta(t, 43, foo2.Float64, closeEnough)
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user