dtoa.c: the 1991 breakthrough that became legacy
1. A problem that looks trivial#
A question from day one of programming: what does echo 0.1 + 0.2 print?
The number 0.1 does not have precise representation in binary form. What is stored is the nearest representable value:
In binary form this is exactly
and the full decimal expansion of that value is 0.1000000000000000055511151231257827021181583404541015625.
A converter must decide how many digits to show and which ones. It has three requirements, and they pull in different directions:
- Correctness. The result must describe exactly the value stored in the
double, correctly rounded. “Approximately” is not acceptable. - Shortest output. Print
0.30000000000000004, not0.3000000000000000444089209850062616169452667236328125. And print0.1, not0.1000000000000000055…. - Speed. The conversion sits on hot paths:
sprintf,serialize,echo,json_encode.
The reverse problem ("string" → double) is the mirror image: read an arbitrarily long decimal number and return the nearest double, exactly as IEEE 754 requires.
How many digits are enough#
A double is a 64-bit IEEE 754 binary64 number: 1 sign bit, 11 exponent bits and 52 stored mantissa bits. The leading bit is implicit, so the significand has bits of precision. Two simple facts follow.
To recover any double from its decimal text, it is enough to print
significant digits. This is the famous %.17g: 17 is the smallest precision that is guaranteed to round-trip every double, so printf("%.17g") became the standard idiom for “dump a float to text without losing anything” in C, and many languages and serializers used it as their fallback. The price is noise in the last digits, as shown below.
Conversely, every decimal string with at most
significant digits survives the trip "string" → double → "string" unchanged.
Between 15 and 17 lies a gray zone where %.17g is safe but produces noise such as 0.10000000000000001. The task “shortest string that reads back as the same number” (shortest round-trip) is exactly about this zone.
2. Gay’s breakthrough#
Until about 1990, printing and reading floating-point numbers in most C libraries was inexact. A typical printf("%.17g") produced digits by doing arithmetic on the double itself and accumulated error. strtod multiplied the mantissa by a power of ten, also in double, and the last bit was sometimes wrong.
Three works appeared almost at once in 1990, and everything later stands on them. Two of them were presented at PLDI, the ACM SIGPLAN Conference on Programming Language Design and Implementation (New York, 1990), and printed in ACM SIGPLAN Notices:
| Work | What it solves |
|---|---|
| Steele, White. How to print floating-point numbers accurately [1] | the Dragon4 algorithm: exact printing with big integers |
| Clinger. How to read floating point numbers accurately [2] | exact reading, with a fast path for short inputs |
| Gay. Correctly rounded binary-decimal and decimal-binary conversions [3] | printing and reading together, with rounding modes |
The first two papers describe algorithms. Gay’s paper reviews both and describes how to make them efficient [3]. He then turned this into code: a single C file, dtoa.c, with both directions in it, dtoa for printing and strtod for reading. The comments in the file name its sources: strtod is “inspired loosely by” Clinger’s paper, and dtoa follows Steele and White.
The oldest entry in its changelog is from June 1991. It was published on netlib, a public repository of numerical software, in the fp directory, under a permissive licence: copy and modify it freely, but keep the notice [4]. From there anyone could take it, and that is what happened. Section 5 shows who took it.
For testing, Gay used the suite by Vern Paxson, David Hough and William Kahan, a base-conversion test program with a report from 1991, one of the first hard tests for this problem. [5]
3. How dtoa.c works#
3.1. A number as an integer, and its rounding interval#
A computer cannot store every real number. A double has only 64 bits, so it can take at most different values, and there are infinitely many reals. The numbers that can be stored form a discrete set: a finite list of points on the number line, with gaps between them. Every other real number has to be rounded to one of these points.
Each point of this set, that is, every finite double, can be written as
Let and be the nearest doubles below and above . Any real number that is closer to than to or is rounded to .
doubles. Open dots are real numbers.Any real number inside reads back as . The shortest-output task is therefore: find a decimal number in with the fewest digits in .
Two small details: a point exactly halfway, and powers of two
What if a number is exactly halfway between two doubles? Then it is equally close to both, and a tie-break rule is needed. IEEE 754 picks the neighbor whose integer is even (round-half-to-even). So the ends of belong to only if of is even. For example, is halfway between and , and it is read as , because that one has even .
What happens at a power of two? The spacing between doubles doubles at every power of two. For the gap below is half the gap above, so is not symmetric: its lower half is half as long as its upper half.
3.2. The Dragon4 idea, as used in dtoa#
To lose nothing, dtoa.c computes exactly. It takes the binary number that the computer stores and converts it to decimal with arbitrary-precision integers (bignums), without floating-point arithmetic. The digits come out one at a time, starting from the most significant one, as in long division. On every turn of the loop the algorithm checks whether it can stop: the digits printed so far may already be enough to tell from every other double, that is, the decimal number lies inside the interval from section 3.1 and reads back as .
Take from section 1. The first digit is . Is already inside ? The distance from to is about , and the half-gap to the neighbors is about . Yes, so the loop stops after one digit and prints 0.1. For the loop needs 17 digits before the check succeeds.
Inside, the algorithm keeps the part of that is not printed yet as a fraction of two bignums. Each turn multiplies by 10, takes the next digit as , and keeps the remainder. The check compares with the half-gaps of the interval, which are stored as two more integers and (in dtoa.c they are called mlo and mhi).
The exact bookkeeping
All three integers are measured in units of one common denominator . At the start equals , scaled by a power of ten so that it is less than 1.
and are the two half-gaps of the interval, written as integers. For an ordinary the gap to each neighbor is , and the half-gap is . To avoid the fraction, all three numbers are multiplied by 2 (and by if ). For a power of two, is twice as large as , as in the details above.
One turn of the loop produces one digit:
Multiplying by 10 moves us one decimal place to the right; are multiplied too, so that they stay in the same units as .
Then the check. There are two candidates for the final result:
- low: the digits printed so far, as they are. This number is below by , and it is inside when .
- high: the same digits with the last one increased to . This number is above by , and it is inside when .
If only low holds, the last digit is . If only high holds, it is . If both hold, we take the one closer to : when , otherwise . If neither holds, the loop goes on to the next digit.
What does this arithmetic cost? The smallest subnormal double is and the largest is about , so and can take about 1100 bits, i.e. a few dozen 32-bit words. Every digit multiplies the whole array by 10. For a typical number that is a lot of work to produce 17 digits.
3.3. What Gay added on top#
Gay did not stop at Dragon4. The file contains several engineering decisions that made it a standard:
- Fast paths without bignums. If few digits are requested and exponents are small, the value is computed with ordinary floating-point arithmetic under error control. Only if the check fails does the bignum path run. These paths trust the hardware, which is a problem of its own (section 6.3).
- Clinger’s fast path in
strtod. If the input has at most 15 significant digits and , the answer is one multiplication or division: Both and (with ) are exactly representable. One IEEE operation on two exact operands is correctly rounded. - Modes 0–9. The mode chooses how the digits are picked; the format itself (
%e,%f,%g) is assembled by the caller from the digits and the decimal point position. Modes 0 and 1 give the shortest string that reads back as the same number. Mode 2 gives a fixed number of significant digits (%e,%g), and mode 3 a fixed number of digits after the point (%f). Modes 4 and 5 are modes 2 and 3 that return a shorter string when one is enough, and modes 6–9 are debugging variants. So one function serves all ofprintf. - Rounding modes (toward zero, up, down) and support for several number formats.
- Its own allocator. Bignums live in free lists (
freelist) and a small static buffer (private_mem), so thatmallocis not called for every digit.
4. Why it was a breakthrough#
Today it is easy to forget what came before. dtoa.c delivered several things at once:
- Correctness in both directions. Printing and reading that agree with each other:
strtod(dtoa(x)) == xfor everyx. - One portable library. A single C file that built on IEEE machines, on VAX, on IBM. It had switches for nearly every machine that existed at the time.
- Enough speed. The fast paths covered “ordinary” numbers.
- A permissive licence. The terms in the header (copy and modify, keep the notice) let everyone take it.
And everyone did. gdtoa lives on in FreeBSD, NetBSD and MinGW, and in Bionic, the C library of Android, where it comes from OpenBSD (strtod.c). The code is vendored in Python, PHP, Ruby (missing/dtoa.c), Chromium (dmg_fp), MySQL (strings/dtoa.cc) and the Firefox tree, which has two copies: SpiderMonkey’s js/src/dtoa.c and NSPR’s dtoa.c.
5. How it got into C-based interpreted languages#
Python#
Before versions 2.7 and 3.1, repr(1.1) returned '1.1000000000000001': it was effectively '%.17g'. In Python 3.1 (2009), and then in 2.7 as a backport (What’s New in Python 2.7), repr learned to return the shortest string that reads back as the same number. The change was made by Eric Smith and Mark Dickinson (bpo-1580). To do it, Gay’s code was brought into the interpreter as Python/dtoa.c. The file header says it was modified for inclusion in the Python core by Dickinson and Smith, and asks that bugs be reported to the Python tracker rather than to Gay. Today the file has 2855 lines, against 4662 in PHP.
It was a very good move: repr became stable and reproducible across platforms (before, the result depended on the C library), and Python gained its own strtod.
PHP#
In PHP, Zend/zend_strtod.c is also a descendant of Gay’s code. In master, before our patch series, it has 4662 lines, of which 312 are conditional-compilation lines (#if, #ifdef). The file header still says that on a machine with IEEE extended-precision registers one must set 53-bit rounding precision before calling strtod or dtoa, for example with _control87(PC_53, MCW_PC). That is a good specimen of the code’s age: an instruction for the x87, needed because of the dependence on the FPU described in section 6.3.
A notable PHP adaptation is state. Gay’s freelist is global; PHP had to replace it with EG(strtod_state).freelist so that the code works in thread-safe (ZTS) builds.
Mode 0 reached PHP 7.1 through the RFC More precise float value handling (Yasuo Ohgaki and Jakub Zelenka). It introduced serialize_precision = -1, which now means “call zend_dtoa in mode 0”. Since then var_export(0.1) prints 0.1, not 0.10000000000000001.
6. Why it is legacy today#
“Legacy” is not an insult here. It means the code did its job, but accumulated structural problems that cannot be fixed locally.
6.1. Speed and memory#
Bignums and free lists still mean working with arrays dozens of words long to produce 17 digits. Modern algorithms use no long arithmetic at all: 64-bit and 128-bit multiplications and a table of powers of ten are enough.
The literature reports that Schubfach and Dragonbox beat Dragon4 by up to a factor of ten (arXiv 2603.06581).
6.2. Size and conditional compilation#
Thousands of lines with branches for VAX, IBM, rounding modes, Honor_FLT_ROUNDS, Sudden_Underflow, Check_FLT_ROUNDS and so on. No real CI builds or tests these branches. The code is practically impossible to read, and risky to change.
For Python and PHP these branches have been dead for a long time: both projects require IEEE 754 and ordinary C.
6.3. Dependence on the FPU#
The result of dtoa.c depends on the FPU. Its fast paths trust the hardware: they are correct only if double arithmetic is exactly IEEE 754 binary64. On x87, which computes in 80-bit registers, a value is rounded twice, first to 64 bits and then to 53, and the last bit of the result can be wrong. The file’s own comment gives 8.3e26 and 6.3876e-16 as inputs of strtod that break this way, and says that one must switch the precision to 53 bits before calling strtod or dtoa. The changelog on netlib has a recent note of the same kind: a 32-bit build with gcc -m32 gives a wrong result for 8.3e26, and -mfpmath=sse fixes it. The bignum path does not have this problem.
Compilers matter here too: whether the code is exact depends on flags like -m32 or -mfpmath=sse, not only on the source. But the fast paths are what makes the code fast, so they cannot simply be dropped.
6.4. Global state#
A shared free list is shared mutable state. It needs a lock or a per-thread copy, as PHP does. In the era of free-threaded Python builds this becomes a real problem rather than a theoretical one.
6.5. Provability#
dtoa.c has no correctness proof. It has 30 years of use and the Paxson–Kahan suite. That counts for a lot, but the netlib changelog shows bugs found after release: 1991, an inefficiency in modes 0 and 1; 1994, strtod with very negative exponents; 1999, an off-by-one in a denormal adjustment (found by David Chase); 2010, wrong directed rounding (Exploring Binary). The code was fixed each time, but its correctness is established only by the passage of time.
The newer algorithms do have proofs: Ryū comes with a correctness proof in Ulf Adams’s paper (PLDI 2018), Schubfach has a write-up by Raffaello Giulietti, and for Żmij (a recent project by Victor Zverovich) the README lists “Formally verified in Lean” among its features.
6.6. Generations of algorithms after Dragon4#
| Generation | Year | Idea |
|---|---|---|
| Dragon4 (Steele, White) | 1990 | exact long arithmetic |
| Grisu (Loitsch) | 2010 | 64-bit integers, but sometimes gives up and falls back to Dragon4 |
| Ryū (Adams) | 2018 | always exact, power-of-ten tables, 128-bit multiplications |
| Schubfach (Giulietti), Dragonbox (Jeon) | 2017–2020 | the same goal, simpler, with proofs |
More on Schubfach in the second article.
7. The goal: a modern replacement#
Given the drawbacks above, we want to propose a modern replacement for dtoa.c. The task is defined by three requirements:
- Same results. For every input, the replacement gives the same output as
dtoa.c, and we can demonstrate it. This lets a project switch without changing behavior. - A significant speed-up. The gain is visible on real programs, not only in microbenchmarks.
- Small and clear code. The project will maintain it for years, so it should be easy to read, review and change.
In the following articles we will discuss what to replace dtoa.c with and how to meet these requirements.
8. What a replacement must do#
Since we are talking about a full replacement and not about one function, it is worth writing down the requirements up front. In Python and PHP, dtoa.c does not do one job but five:
- shortest output (mode 0);
- a given number of significant digits (mode 2);
- a given number of digits after the decimal point, including negative values (mode 3);
strtod: reading, with an overflow error (errno = ERANGE);- thread safety and its own allocator.
Most modern algorithms cover only item 1. That is why “just take Ryū” does not work. More on this in the next articles.
Sources#
[1] Guy L. Steele Jr., Jon L. White. How to print floating-point numbers accurately. PLDI 1990; ACM SIGPLAN Notices 25(6), June 1990, pp. 112–126. doi:10.1145/93542.93559. Walkthrough: Ryan Juckett.
[2] William D. Clinger. How to read floating point numbers accurately. PLDI 1990; ACM SIGPLAN Notices 25(6), June 1990, pp. 92–101. doi:10.1145/93542.93557. Free copy: University of Oregon ScholarsBank.
[3] David M. Gay. Correctly rounded binary-decimal and decimal-binary conversions. AT&T Bell Laboratories, Numerical Analysis Manuscript 90-10, Murray Hill, NJ, November 30, 1990. PDF.
[4] David M. Gay. dtoa.c, netlib: the file, changelog.
[5] Vern Paxson, David Hough, William Kahan. Base-conversion test program (testbase) and its report, 1991. netlib.org/fp/testbase.
Further reading:
- What’s New in Python 3.1, the section on float
repr - Python issue 7117 and commit r75651
- PHP RFC: precise float value
- Exploring Binary: Incorrect Directed Conversions in David Gay’s strtod()
- Drachennest (Grisu, Ryū, Schubfach, Dragonbox in one place), Dragonbox
- arXiv 2603.06581