I'm thrilled to share DecimalAnnex, an implementation of IEEE 754 128-bit decimal floating-point arithmetic in native Swift. I hope you'll find it to be as fun to use as I did to make! It's fast, conformant, and tailored specifically for the language we have.
Why now?
Some of you may have followed along as I've proposed ways to speed up and improve the precision of Foundation.Decimal. If that particular format is what you want or need, I hope that upcoming releases will give your use cases a boost.
But there are some standard floating-point behaviors that the legacy type can't and probably won't ever accommodate, including infinity and signed zero. Others have pointed to its lack of a guaranteed storage width that makes serialization awkward, partly a legacy issue and partly a policy decision out of our hands.
I started this Decimal128 implementation over two years ago to gain a sense of how I'd want to approach the problem. For example, instead of computing log10 by log2 estimate followed by table lookup, I learned that in some scenarios we can profit from using the estimate directly. I carried over some of these learnings into Foundation.Decimal; others I picked up while working on the Foundation type. I've now taken that experience back to Decimal128 and completed the work manually.
(Could I have vibe-coded the whole thing in a morning? For reference, I tried this: it works, but either the code is elegant and the performance lacking, or the code gets gnarly pretty fast. This isn't to claim that LLMs have played no role during the bring-up of this library: they've been very helpful in analyzing code for overlooked think-os, prototyping fast paths, and pulling together test harnesses--they love 'oracles,' for some reason.)
Why Swift?
The shortest path to a working Decimal128 implementation would be to wrap, say, Intel's reference implementation in C, taking advantage of Swift's seamless interoperability. (I tried this too: it works as well.) But that would deprive us of some advantages of a full native implementation:
First, if you wrap another implementation, yours won't ever be faster than theirs. Turns out, it's quite possible to make that happen when you control all of the code:
| Operation | DecimalAnnex 0.1.5 |
Intel 2.0U5 |
Boost21bb2ed |
Foundation macOS 26.7 |
|---|---|---|---|---|
| Add | 9.2 | 10.5 | 15.4 | 401.8 |
| Subtract | 9.2 | 11.6 | 15.0 | 387.5 |
| Multiply | 5.7 | 20.1 | 5.5 | 310.8 |
| Divide | 29.0 | 38.7 | 74.1 | 1447.6 |
| Fused multiply-add | 19.6 | 33.1 | 35.8 | — |
| Round to integer, ties to even | 16.7 | 9.1 | 5.4 | 470.8 |
Timings shown are ns/op on Apple M2 Pro for an 'everyday' mixture of operands.
(It took 60 lines of code to speed up round to integer, for which I tagged version 0.1.6.)
While writing this implementation, I was particularly mindful that I wasn't planning also to provide Decimal64 and Decimal32 (at least for now). Therefore, it made sense to optimize performance with smaller operands so you don't pay for what you don't use. For example, many operations use fast paths when operands' raw significands fit in 64 bits.
I also wanted to anticipate arithmetic that users are likely to perform in Swift. For example, though there's a dedicated operation for scaling by powers of ten (spelled init(sign:exponent:significand:) in Swift), if you want to write x * 10 or x / 1000, there's a fast path for that. Unless I want to eke out every last drop of performance, I now don't think much before writing let x: Decimal128 = 42/100. (That may even optimize down to constant on a good day.)
Second, if you wrap another implementation, it's difficult for you to be more standards-compliant than they are.
In the course of this work, I've reported one bug to Intel (in division--a fix will issue soon) and have several more I'll one day write up, showing how independent implementations can contribute back to existing work.
The Boost C++ implementation is another very good and actively developed candidate for wrapping in Swift, but it doesn't guarantee that arithmetic results will select the standard's preferred quantum (the represented exponent that distinguishes 1.0 from 1.000). This implementation does while still remaining competitive in performance.
Third, if you wrap another implementation, it'll take deliberate work to adapt its behavior to align with the facilities, conventions, and challenges of a native type in Swift; in some cases, that's likely more easy to achieve and maintain when you can reach deep into the implementation itself.
This implementation deliberately parses text just as the standard library's floating-point types do. For example, it rejects strings such as "1.000E1E" or "NAN123" while accepting parenthesized NaN payloads such as "-nan(0x123)". When printing, all NaN values are represented as "nan", but when debug printing, the sign and payload of NaN are serialized--again, just like Float or Double.
Decimal128 also provides proper generic initializers for converting to and from fixed-width integer types of arbitrary bit width as well as binary floating-point types up to 128 bits. (See the test target for how we exercise this functionality for non-existent types.)
There's also the fun bit about providing APIs that take a FloatingPointRoundingRule without substantially affecting performance. Turns out, as with some Unicode APIs, the use of a non-frozen enum on ABI-stable platforms can present a problem: for arithmetic that could take 5–10 ns per operation, an overhead of several nanoseconds is rather suboptimal.
So I figured out a way to expose FloatingPointRoundingRule at the API boundary, while using an internal enum of defined memory size at the ABI boundary and in the implementation (the internal typing being declared using @objc, inspired by discussions in a recent Evolution proposal). If you only ever use the default rounding rule, it all compiles down to a constant integer: again, you don't pay for what you don't use.
This implementation has also tried to tackle the problem that Swift's float literals are passed into init(floatLiteral:) as a binary floating-point value. You likely wouldn't want your Decimal128 literal initializer creating a rounded value based on what Double or Float80 can represent.
Therefore, as it is, I've chosen not to conform this type to ExpressibleByFloatLiteral. Instead, I've implemented a macro (which you can omit by disabling a package trait). The macro allows #Decimal128(1.0) to compile down to a specific bit pattern; as the exact representation of the argument is accessible to the macro, we never round through a binary floating-point intermediary. As a bonus, 1.00, 1.0, 1 also preserve their distinct represented exponents and roundtrip back to String (and so too does the sign of -0). The macro will also warn if you write a literal that requires more precision than Decimal128 can represent exactly; it'll even provide you a fix-it with the nearest representable finite value if one exists. Basically, it's what we'd want float literals to do one day in the standard library; for now, it's fortunate we have a way to achieve it outside the compiler.
What's left to do?
This work has been tested extensively against out-of-repository published corpora from Intel, IBM, and Cairo University. That test harness needs clean-up and the few expected, standards-compliant divergences (in string syntax, and in NaN sign and payload handling) need to be documented.
As with the standard library's binary floating-point types, there's no implementation of the optional but recommended transcendental functions (e.g., sin, cos). Users can choose to wrap an existing reference implementation to obtain those results, or they can convert to Double and use swift-numerics. This is likely beyond what I'll find edifying to reimplement in Swift, though I have the textbook on the subject already on my bookshelf for reading some day.
Also great
This package is laser-focused on one specific decimal format, and so it's not based on some past work that's more ambitious in scope, but they are certainly worth mentioning to check out if you're shopping for decimal floating-point types: