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:

0.1000000000000000055511151231257827…0.1000000000000000055511151231257827\ldots

In binary form this is exactly

0.1≈7205759403792794×2−56=0x1.999999999999a×2−40.1 \approx 7205759403792794 \times 2^{-56} = \texttt{0x1.999999999999a} \times 2^{-4}

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:

  1. Correctness. The result must describe exactly the value stored in the double, correctly rounded. “Approximately” is not acceptable.
  2. Shortest output. Print 0.30000000000000004, not 0.3000000000000000444089209850062616169452667236328125. And print 0.1, not 0.1000000000000000055….
  3. 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 p=53p = 53 bits of precision. Two simple facts follow.

To recover any double from its decimal text, it is enough to print

⌈plog⁡102⌉+1=⌈15.95⌉+1=17\lceil p \log_{10} 2 \rceil + 1 = \lceil 15.95 \rceil + 1 = 17

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

⌊(p−1)log⁡102⌋=⌊15.65⌋=15\lfloor (p-1)\log_{10} 2 \rfloor = \lfloor 15.65 \rfloor = 15

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 2642^{64} 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

v=m⋅2e,m∈N, m<253.v = m \cdot 2^{e}, \qquad m \in \mathbb{N},\ m < 2^{53}.

Let v−v^- and v+v^+ be the nearest doubles below and above vv. Any real number that is closer to vv than to v−v^- or v+v^+ is rounded to vv.

v− v v+ I halfway halfway reads as v reads as v+
Filled dots are doubles. Open dots are real numbers.

Any real number inside II reads back as vv. The shortest-output task is therefore: find a decimal number d⋅10kd \cdot 10^{k} in II with the fewest digits in dd.

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 mm is even (round-half-to-even). So the ends of II belong to II only if mm of vv is even. For example, 90071992547409939007199254740993 is halfway between 90071992547409929007199254740992 and 90071992547409949007199254740994, and it is read as 90071992547409929007199254740992, because that one has even mm.

What happens at a power of two? The spacing between doubles doubles at every power of two. For v=2kv = 2^k the gap below is half the gap above, so II 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 vv from every other double, that is, the decimal number lies inside the interval II from section 3.1 and reads back as vv.

Take v=0.1000000000000000055…v = 0.1000000000000000055\ldots from section 1. The first digit is 11. Is 0.10.1 already inside II? The distance from 0.10.1 to vv is about 5.6⋅10−185.6 \cdot 10^{-18}, and the half-gap to the neighbors is about 6.9⋅10−186.9 \cdot 10^{-18}. Yes, so the loop stops after one digit and prints 0.1. For 0.1+0.20.1 + 0.2 the loop needs 17 digits before the check succeeds.

Inside, the algorithm keeps the part of vv that is not printed yet as a fraction R/SR/S of two bignums. Each turn multiplies RR by 10, takes the next digit as ⌊R/S⌋\lfloor R/S \rfloor, and keeps the remainder. The check compares RR with the half-gaps of the interval, which are stored as two more integers M−M^{-} and M+M^{+} (in dtoa.c they are called mlo and mhi).

The exact bookkeeping

All three integers are measured in units of one common denominator SS. At the start R/SR/S equals vv, scaled by a power of ten so that it is less than 1.

M−M^{-} and M+M^{+} are the two half-gaps of the interval, written as integers. For an ordinary v=m⋅2ev = m \cdot 2^{e} the gap to each neighbor is 2e2^{e}, and the half-gap is 2e−12^{e-1}. To avoid the fraction, all three numbers are multiplied by 2 (and by 2−e2^{-e} if e<0e < 0). For a power of two, M+M^{+} is twice as large as M−M^{-}, as in the details above.

One turn of the loop produces one digit:

R←10 R,di=⌊RS⌋,R←R mod S,M±←10 M±.R \leftarrow 10\,R, \qquad d_i = \left\lfloor \frac{R}{S} \right\rfloor, \qquad R \leftarrow R \bmod S, \qquad M^{\pm} \leftarrow 10\,M^{\pm}.

Multiplying by 10 moves us one decimal place to the right; M±M^{\pm} are multiplied too, so that they stay in the same units as RR.

Then the check. There are two candidates for the final result:

  • low: the digits printed so far, as they are. This number is below vv by R/SR/S, and it is inside II when R<M−R < M^{-}.
  • high: the same digits with the last one increased to di+1d_i + 1. This number is above vv by (S−R)/S(S - R)/S, and it is inside II when R+M+>SR + M^{+} > S.

If only low holds, the last digit is did_i. If only high holds, it is di+1d_i + 1. If both hold, we take the one closer to vv: did_i when 2R<S2R < S, otherwise di+1d_i + 1. If neither holds, the loop goes on to the next digit.

What does this arithmetic cost? The smallest subnormal double is 2−10742^{-1074} and the largest is about 210242^{1024}, so RR and SS 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 ∣e10∣≤22|e_{10}| \le 22, the answer is one multiplication or division: result=fl⁡(w⋅10e) or fl⁡(w/10−e).\text{result} = \operatorname{fl}\bigl(w \cdot 10^{e}\bigr) \ \text{or} \ \operatorname{fl}\bigl(w / 10^{-e}\bigr). Both w<253w < 2^{53} and 1022=222⋅52210^{22} = 2^{22}\cdot 5^{22} (with 522<2535^{22} < 2^{53}) 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 of printf.
  • 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 that malloc is 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:

  1. Correctness in both directions. Printing and reading that agree with each other: strtod(dtoa(x)) == x for every x.
  2. 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.
  3. Enough speed. The fast paths covered “ordinary” numbers.
  4. 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:

  1. shortest output (mode 0);
  2. a given number of significant digits (mode 2);
  3. a given number of digits after the decimal point, including negative values (mode 3);
  4. strtod: reading, with an overflow error (errno = ERANGE);
  5. 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:

← All posts