Repository navigation
Format float32 fields with float32 precision in ReflectFrom - #448
Conversation
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 go-ini#447
unknwon
left a comment
There was a problem hiding this comment.
Thanks, the formatting fix is right, but the read side needs a matching change.
MapTo still parses float32 fields as a float64 and then narrows them, which rounds twice. I ran all 2³² float32 bit patterns through format → ParseFloat(s, 64) → float32. One value (and its negative) comes back wrong: bits 0x15ae43fd is written as 7.038531e-26 and reads back one ULP off as 7.0385313e-26. Main doesn't have this problem because it writes all 17 digits.
Fix in parseValue (struct.go line 214). GitHub won't take a suggestion on that line because it's outside this PR's diff:
case reflect.Float32, reflect.Float64:
- f, err := strconv.ParseFloat(str, 64)
+ f, err := strconv.ParseFloat(str, t.Bits())The suggestion below adds a regression test for it.
| 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) |
There was a problem hiding this comment.
Regression case for the double rounding. It fails without the ParseFloat change (expected 7.038531e-26, actual 7.0385313e-26):
| 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) |
Describe the pull request
ReflectFromwrote afloat32field with float64 digits:0.1became0.10000000149011612,1.1became1.100000023841858.formatValueprintedv.Float(), which is the float32 widened to float64.Now the
reflect.Float32kind is printed asfmt.Sprint(float32(v.Float())). That is the shortest string that parses back to the same float32, soMapTostill reads the exact value.float64is unchanged. Covers plain fields,*float32and named float32 types.New
TestStructRoundTrip_Float32writesF = 0.1,FP = 1.1,M = 2.2and reads them back. It fails on main and passes with the change. I also checked 2M random float32 bit patterns: format then parse gives the same value for all of them.go test -race -count=1 ./...,go vet ./...andgofmt -l .pass locally (Go 1.26.5, macOS arm64). I did not run golangci-lint locally.Link to the issue: #447
Checklist
AI usage
This PR was made with an AI coding agent (Claude): it found the bug while fuzzing the struct round trip, wrote the fix and test, and ran the checks above. No human reviewed it before opening.