Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion struct.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,11 @@ func formatValue(v reflect.Value) (string, error) {
return fmt.Sprint(v.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return fmt.Sprint(v.Uint()), nil
case reflect.Float32, reflect.Float64:
case reflect.Float32:
// Formatted as a float32, so 0.1 is written as 0.1 and not as the
// float64 0.10000000149011612.
return fmt.Sprint(float32(v.Float())), nil
case reflect.Float64:
return fmt.Sprint(v.Float()), nil
}
return "", fmt.Errorf("unsupported type %q", t)
Expand Down
24 changes: 24 additions & 0 deletions struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1377,6 +1377,30 @@ func TestStructRoundTrip_Uint8(t *testing.T) {
assert.Equal(t, "B = 200\nBP = 7\n", string(data))
}

func TestStructRoundTrip_Float32(t *testing.T) {
type myFloat float32
type cfg struct {
F float32
FP *float32
M myFloat
D float64
}
fp := float32(1.1)
in := cfg{F: 0.1, FP: &fp, M: 2.2, D: 0.1}

data, err := marshal(in)
require.NoError(t, err)
assert.Equal(t, "F = 0.1\nFP = 1.1\nM = 2.2\nD = 0.1\n", string(data))

var out cfg
require.NoError(t, unmarshal(data, &out))
assert.Equal(t, in.F, out.F)
require.NotNil(t, out.FP)
assert.Equal(t, fp, *out.FP)
assert.Equal(t, in.M, out.M)
assert.Equal(t, in.D, out.D)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regression case for the double rounding. It fails without the ParseFloat change (expected 7.038531e-26, actual 7.0385313e-26):

Suggested change
assert.Equal(t, in.D, out.D)
assert.Equal(t, in.D, out.D)
// Parsing this one as a float64 and then narrowing it to a float32 rounds
// twice and lands one ULP off.
in = cfg{F: 7.038531e-26, FP: &fp}
data, err = marshal(in)
require.NoError(t, err)
out = cfg{}
require.NoError(t, unmarshal(data, &out))
assert.Equal(t, in.F, out.F)

}

// https://github.com/go-ini/ini/issues/274
func TestMapTo_EmbeddedPointerKeepsValues(t *testing.T) {
type Base struct{ A, B string }
Expand Down
Loading