From: "sferik (Erik Berlin) via ruby-core" Date: 2026-11-19T18:16:56+00:00 Subject: [ruby-core:127629] [Ruby Bug#22609] String#to_f misrounds numbers close to halfway between two Floats on 32-bit x86 with x87 Issue #22609 has been reported by sferik (Erik Berlin). ---------------------------------------- Bug #22609: String#to_f misrounds numbers close to halfway between two Floats on 32-bit x86 with x87 https://bugs.ruby-lang.org/issues/22609 * Author: sferik (Erik Berlin) * Status: Open * ruby -v: ruby 3.4.13 (2026-11-19 revision 48857d6f2e) +PRISM [i686-linux] * Backport: 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN ---------------------------------------- On 32-bit x86 builds that use the x87 FPU for floating point, `String#to_f` sometimes returns the wrong one of two neighboring Floats when the number is very close to halfway between them. The same goes for `Float()` and `Marshal.load`, which also go through `ruby_strtod`. ```ruby "139090927331892.61718749".to_f #=> 139090927331892.62 ``` That number is between the Floats 139090927331892.609375 and 139090927331892.625, and it is just below the halfway point between them, 139090927331892.6171875. So I expect 139090927331892.61, which is what x86_64 and arm64 return. A few more examples, with the result on i686-linux and the one I expect: ```ruby "1022987641419180.18749".to_f #=> 1022987641419180.2, expected 1022987641419180.1 "121374757949434.89843749".to_f #=> 121374757949434.9, expected 121374757949434.89 ``` I reproduced it with the official `i386/ruby:3.4` Docker image: ``` $ docker run --rm --platform linux/386 i386/ruby:3.4 ruby -e 'p "139090927331892.61718749".to_f' 139090927331892.62 ``` Current master behaves the same. I compiled master's missing/dtoa.c with the gcc in that image, where `FLT_EVAL_METHOD` is 2, and called its `strtod` directly. Of the 7 numbers in the test I'm adding, 5 came out as the wrong Float, including all three above. The comment at the top of missing/dtoa.c explains why: > On a machine with IEEE extended-precision registers, it is necessary to specify double-precision (53-bit) rounding precision before invoking strtod or dtoa. Ruby doesn't do that. With the x87 control word at its usual 64-bit precision, intermediate results in `strtod` are rounded to 64 bits first and then again to 53 bits when they are stored, and that double rounding can land on the wrong Float. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/