Skip to content

Parse float32 fields with float32 precision in MapTo - #449

Merged
unknwon merged 1 commit into
mainfrom
fix-float32-parse-precision
Nov 18, 2026
Merged

unknwon merged 1 commit into
mainfrom
fix-float32-parse-precision

Conversation

@unknwon

@unknwon unknwon commented Nov 18, 2026

Copy link
Copy Markdown
Member

Describe the pull request

Follow-up to #448. That PR made ReflectFrom write float32 fields as the shortest float32 string, but MapTo still parsed them with strconv.ParseFloat(str, 64) and then narrowed to float32. Rounding twice (text → float64 → float32) isn't always the same as rounding once. Running all 2³² float32 bit patterns through format → parse found one value, and its negative, that came back wrong: bits 0x15ae43fd is written as 7.038531e-26 and read back one ULP off as 7.0385313e-26. Before #448 this value round-tripped, because all 17 digits were written.

parseValue now parses with strconv.ParseFloat(str, t.Bits()), so float32 fields round once, to the nearest float32. With this change, every finite float32 round-trips exactly.

TestStructRoundTrip_Float32 gets a case for 7.038531e-26. It fails without the fix and passes with it. go test -race ./..., go vet ./... and gofmt -l . pass.

One side effect: an out-of-range float32 such as 1e39 now fails with strconv's "value out of range" error instead of "value … overflows float32". No test checks that message.

Link to the issue: #447

Checklist

  • I agree to follow the Code of Conduct by submitting this pull request.
  • I have read and acknowledge the Contributing guide.
  • I have added test cases to cover the new code.

AI usage

Made with Amp (Claude). It found the double rounding by checking every float32 bit pattern while reviewing #448, then wrote the fix and the test and ran the checks above.

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.
@unknwon
unknwon merged commit f8c5007 into main Nov 18, 2026
7 checks passed
@unknwon
unknwon deleted the fix-float32-parse-precision branch November 18, 2026 16:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant