镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

[rtext] Fix TextToFloat() rounding and add exponent support - #6313

Open
jayhemnani9910 wants to merge 2 commits into
raysan5:masterfrom
jayhemnani9910:fix-text-to-float-precision
Open

jayhemnani9910 wants to merge 2 commits into
raysan5:masterfrom
jayhemnani9910:fix-text-to-float-precision

Conversation

@jayhemnani9910

@jayhemnani9910 jayhemnani9910 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

TextToFloat() adds each digit to a float divided by a growing float divisor, so the rounding error adds up, and it stops at e:

TextToFloat("98537.3594324");  // 98537.3516 (atof: 98537.3594)
TextToFloat("78042.73");       // 78042.7344 (atof: 78042.7266)
TextToFloat("1e3");            // 1          (atof: 1000)
TextToFloat("1.5e-2");         // 1.5        (atof: 0.015)

Out of 100000 random decimals (up to 5 integer and 7 fraction digits), 26864 differ from (float)strtod().

Up to 9 significant digits are now read into an unsigned int (later ones only move the decimal point) and scaled once by an exact float power of ten (steps of 1e10 beyond that), and an optional e/E exponent is read. No doubles. Still '.' only, and signs, leading text and junk after the number behave as before.

Against strtof(), worst error in ULPs (1 ULP is the gap to the next float):

Strings before now
100000 short decimals (up to 5 integer and 7 fraction digits) 28% differ, up to 3 ULP 7.7% differ, at most 1 ULP
1M random floats printed with %.9g 89% differ, some far off 29% differ, at most 3 ULP
300000 strings with signs, fractions and exponents 98% differ, some far off 33% differ, at most 3 ULP

Edge cases: 1e, e5, .e1, 0e999 give what strtof gives, 1e999 is inf, 1e-45 is the smallest subnormal, and every float in [3e38, FLT_MAX) printed with %.9g reads back finite. One limit: the 8-digit 3.4028235e38 rounds up to inf (strtof gives FLT_MAX).

Comment thread src/rtext.c Resolved

This branch has not been deployed

No deployments
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.

2 participants