Skip to content

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

Merged
raysan5 merged 3 commits into
raysan5:masterfrom
jayhemnani9910:fix-text-to-float-precision
Nov 11, 2026
Merged

raysan5 merged 3 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
Comment thread src/rtext.c Resolved
@jayhemnani9910

Copy link
Copy Markdown
Contributor Author

Done in b8c18ac, the static array is gone. The last power of ten (at most 1e10) is now built with a small loop of *10.0f. Every step is exact in a float, so the results are the same as before.

I checked it against the previous commit on 1,000,000 random decimals (with signs, fractions and exponents) plus edge cases: 0 bit differences. The headless lib (PLATFORM_MEMORY) builds without new warnings.

@raysan5
raysan5 merged commit fbcb683 into raysan5:master Nov 11, 2026
16 checks passed
@raysan5

raysan5 commented Nov 11, 2026

Copy link
Copy Markdown
Owner

@jayhemnani9910 thanks for the redesign

@jayhemnani9910
jayhemnani9910 deleted the fix-text-to-float-precision branch November 13, 2026 14:33
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