Skip to content

String#to_f and Float() return wrong values for numeric strings longer than 79 characters #7846

Closed

Description

@yuyongyan29-dev

mrb_str_len_to_dbl() (src/string.c) copies the input into a fixed char buf[DBL_DIG * 4 + 20] (80 bytes)
before calling mrb_read_float(). When the input does not fit:

  • with no . seen yet, it returns INFINITY (positive, even for a negative number);
  • with a . seen, it stops copying, so the rest of the fraction and the exponent are dropped.

The copy happens for every string without spaces, not just ones with _, so ordinary long inputs (leading
zeros, long fractions produced by other tools, etc.) are affected.

Reproduction (master 8587881, plain rake build):

p ("0" * 80 + "1").to_f          # => Infinity   (expected 1.0)
p ("0" * 100).to_f               # => Infinity   (expected 0.0)
p ("-" + "0" * 100 + "5").to_f   # => Infinity   (expected -5.0)
p ("1" * 100).to_f               # => Infinity   (expected 1.111111111111111e+99)
p ("1." + "0" * 80 + "e5").to_f  # => 1.0        (expected 100000.0)
p ("0." + "0" * 80 + "1").to_f   # => 0.0        (expected 1.0e-81)
p Float("0" * 80 + "1")          # => Infinity   (expected 1.0)
p Float("1." + "0" * 80 + "e5")  # => 1.0        (expected 100000.0)

The same inputs one or two characters shorter work, e.g. ("0" * 78 + "1").to_f is 1.0 and
("1." + "0" * 70 + "e5").to_f is 100000.0. ("0" * 80 + "1").to_i is 1. CRuby 3.3 gives the expected
values above for all of these.

Expected: the result should not depend on the length of the string; leading zeros and extra fraction digits
should not change the value, and the exponent should always be applied.

A possible direction: only copy when an underscore actually has to be removed, and use a buffer sized from
len (or skip leading zeros / drop surplus fraction digits while still copying the exponent) instead of
bailing out at 80 bytes.

Environment: Linux x86-64 (Debian 13), gcc 14, default build config.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions