From 8c0a8d976be6c9b8010acd52cf327c5dc341fe06 Mon Sep 17 00:00:00 2001 From: bardrop Date: Wed, 18 Nov 2026 12:21:05 +0530 Subject: [PATCH] Format float32 fields with float32 precision in ReflectFrom ReflectFrom wrote a float32 0.1 as 0.10000000149011612 because formatValue printed the value widened to float64. Format the float32 kind as a float32, which still parses back to the same value. Fixes #447 --- struct.go | 6 +++++- struct_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/struct.go b/struct.go index 25db8ff..cf36678 100644 --- a/struct.go +++ b/struct.go @@ -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) diff --git a/struct_test.go b/struct_test.go index 59625b4..fa48cd2 100644 --- a/struct_test.go +++ b/struct_test.go @@ -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) +} + // https://github.com/go-ini/ini/issues/274 func TestMapTo_EmbeddedPointerKeepsValues(t *testing.T) { type Base struct{ A, B string }