From 83393b357510337435e778d8c5263f4aa0cf23dc Mon Sep 17 00:00:00 2001 From: Joe Chen Date: Wed, 18 Nov 2026 16:04:50 +0000 Subject: [PATCH] Parse float32 fields with float32 precision in MapTo Parsing as a float64 and then narrowing to a float32 rounds twice, so the shortest float32 string for some values, such as 7.038531e-26, read back one ULP off. --- struct.go | 2 +- struct_test.go | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/struct.go b/struct.go index cf36678..2fcd025 100644 --- a/struct.go +++ b/struct.go @@ -211,7 +211,7 @@ func parseValue(t reflect.Type, str string) (reflect.Value, error) { } v.SetUint(u) case reflect.Float32, reflect.Float64: - f, err := strconv.ParseFloat(str, 64) + f, err := strconv.ParseFloat(str, t.Bits()) if err != nil { return v, err } diff --git a/struct_test.go b/struct_test.go index fa48cd2..684aafa 100644 --- a/struct_test.go +++ b/struct_test.go @@ -1399,6 +1399,15 @@ func TestStructRoundTrip_Float32(t *testing.T) { assert.Equal(t, fp, *out.FP) assert.Equal(t, in.M, out.M) 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