Extracting Values from Decimal
November 2026 ・ 2,100 words
Whenever I need to deal with Decimal values I’m surprised by how inconsistent and incomplete the API for this type still is. For instance, there’s no way to round a Decimal without using C functions, despite people requesting it for years. It’s also somehow impossible to convert a Decimal to a double or integer directly without going via NSDecimalNumber. So I thought it would be interesting to build these conversions myself.
What is a Decimal?
Decimal types are used to represent very large numbers or very high precision numbers exactly, without the rounding errors inherent to binary floating-point types like Double. For example the number 1234567890123.456789012345 can be stored exactly in a Decimal whereas using Double would round this off to only 4 decimal places:
let str = "1234567890123.456789012345"
Decimal(string: str) // 1234567890123.456789012345
Double(str) // 1234567890123.4568
This is important for some use cases like financial values where rounding errors are unacceptable. However, this precision comes at the cost of memory usage: a Decimal is 20 bytes compared to 8 bytes for Double.
To get technical, Decimal has a 128-bit significand (unshifted number) compared to 52 bits for Double, which results in approximately 38 versus 16 decimal digits of precision.
The different decimal types
NSDecimalNumber
In Objective-C decimals are typically represented with the NSDecimalNumber class. The API is reasonably good — decimals can be converted to and from strings and doubles or any other numeric type thanks to it inheriting from NSNumber. Performing mathematical operations is not ideal due to ObjC not having operator overloading, but it is possible:
num1 = [num1 decimalNumberByAdding:num2];
However, rounding values is painful. Here’s how to round an NSDecimalNumber to two decimal places:
NSDecimalNumber *num = [[NSDecimalNumber alloc] initWithDouble:123.4567];
NSDecimalNumberHandler *handler =
[[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundPlain
scale:2
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:NO];
num = [num decimalNumberByRoundingAccordingToBehavior:handler];
The NSDecimalNumber class is also available in Swift, though strangely enough with the same cumbersome API. Apple didn’t improve the interface for Swift at all:
var num = NSDecimalNumber(123.4567)
let handler = NSDecimalNumberHandler(
roundingMode: .plain,
scale: 2,
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: false
)
num = num.rounding(accordingToBehavior: handler)
There aren’t even default values on that NSDecimalNumberHandler initialiser 😓
NSDecimal
There is also an NSDecimal struct type in Objective-C. Unlike structs in Swift, C structs cannot have functions attached to them. So what do NSDecimal operations look like?
NSDecimalMultiply(&result, &num1, &num2, NSRoundPlain);
NSDecimalRound(&result, &num, 2, NSRoundPlain);
Not very ergonomic, but that’s typical for C APIs. At least rounding can be done in a single line!
Decimal
NSDecimal is imported into Swift as Decimal, and it has some nice Swift conveniences added. For example, it adds a failable initialiser for string parsing and standard mathematical operators (+ - * /).
However, there are a couple of glaring omissions. Rounding must still be done using NSDecimalRound and amazingly, there is no way to directly extract the value as a Double or any other numeric type.
Here’s a summary of the sad situation:
| NSDecimal | NSDecimalNumber | Decimal | |
|---|---|---|---|
| Language | ObjC | ObjC & Swift | Swift |
| Type | Struct | Class | Struct |
| Math operations | C functions | Methods | Operators |
| Rounding | OK | Painful | Awkward |
Extract Double |
No | Yes | No |
It shows that Decimal is really the type to use in Swift, but it still has these weird C functions for some functionality like rounding. That one can be fixed easily at least:
extension Decimal {
mutating func round(places: Int = 0, mode: RoundingMode = .plain) {
var result = Decimal.nan
NSDecimalRound(&result, &self, places, mode)
self = result
}
}
How about extracting Double values though?
Converting Decimal to Double
Sometimes converting to a less-precise type is unavoidable since many APIs and serialisation formats don’t support Decimal directly. A Decimal can be converted to a Double, but it must be bridged to NSDecimalNumber first:
let num = Decimal(123.45)
let dbl = (num as NSDecimalNumber).doubleValue
This actually has to allocate an NSDecimalNumber object on the heap, since NSDecimal is too big to fit into a tagged pointer. There’s literally no other way to extract a numeric value directly from Decimal (don’t even joke about converting it via String).
That bugs me. Surely it can’t be that hard to convert Decimal to another numeric type.
Digging into Decimal
Since Decimal is really an NSDecimal C struct, there’s no concept of private properties and thus nothing stopping me from examining its internal fields. Here’s how it’s defined in the headers:
typedef struct {
signed int _exponent:8;
unsigned int _length:4;
unsigned int _isNegative:1;
unsigned int _isCompact:1;
unsigned int _reserved:18;
unsigned short _mantissa[8];
} NSDecimal;
I wouldn’t normally recommend accessing the internal fields of a type, and Swift usually prevents us from doing so. Relying on the memory layout of a field to cast it to a different type (as I do below) is even less safe. But C structs don’t have the same concept of private data, and this layout hasn’t changed for decades. Unit tests will catch it if it ever does change.
Those first five members are C bit fields and are all packed into a single 32-bit int. The _mantissa is an array of 8× 16-bit ints.
I’ve always found binary floating-point numbers like Double a bit hard to visualise, but decimal floating-point numbers are much simpler. The mantissa (or significand) is a huge 128-bit integer value, and the exponent effectively shifts the decimal point left or right:
| Mantissa | Exponent | Value |
|---|---|---|
| 12345 | 0 | 12,345 |
| 12345 | 1 | 123,450 |
| 12345 | 2 | 1,234,500 |
| 12345 | 4 | 123,450,000 |
| 12345 | 8 | 1,234,500,000,000 |
| 12345 | -1 | 1,234.5 |
| 12345 | -2 | 123.45 |
| 12345 | -4 | 1.2345 |
| 12345 | -8 | 0.00012345 |
Since the exponent can be anything from -128 to 127 and is combined with a 128-bit mantissa, it’s clear that Decimal can accurately represent a phenomenal range of numeric values.
So how can I use these fields to get the value as a Double?
Extracting floating-point values
The representation of a decimal is: sign × mantissa × 10 exponent, so the conversion should be as straightforward as:
- Convert the mantissa to a single unsigned value
- Multiply it by
pow(10, exponent) - Negate if
isNegative
Convert the mantissa
The first problem is that the _mantissa array gets bridged to Swift as a big tuple of eight UInt16, which is a hassle to use. One way is to accumulate each part into a total and shift by 216 each time:
let mult = 0x1p16 // 65536
var result = Double(_mantissa.7)
result = result * mult + Double(_mantissa.6)
result = result * mult + Double(_mantissa.5)
result = result * mult + Double(_mantissa.4)
result = result * mult + Double(_mantissa.3)
result = result * mult + Double(_mantissa.2)
result = result * mult + Double(_mantissa.1)
result = result * mult + Double(_mantissa.0)
That
0x1p16value is a floating-point hex literal with a binary exponent, equal to 1 × 216
Hopefully this will be bridged to the new InlineArray type instead of a tuple in future to make this easier.
There’s another alternative using “unsafe” memory access, by treating the 8 contiguous UInt16 fields as two UInt64 values:
var mantissa = _mantissa
let (low, high): (UInt64, UInt64) = withUnsafePointer(to: &mantissa) {
$0.withMemoryRebound(to: UInt64.self, capacity: 2) {
($0[0], $0[1])
}
}
var result = Double(high) * 0x1p64 + Double(low)
This method avoids that unwieldy tuple syntax and it turns out it is also slightly faster.
Swift also has a new
UInt128type but converting that to aDoubleis very slow. Splitting it into high and lowUInt64values and converting each to aDoubleworks but then it’s essentially no different to this code, and it’s only supported on the newest runtime versions.
Shift by the exponent
The next step is to multiply by 10 to the power of the exponent:
result *= pow(10, Double(_exponent))
This also handles negative exponents, like multiplying by 0.1, 0.01 etc.
Simple enough, but there is one slight hitch with this. I wanted my decimal-to-double conversion to produce the exact same value as NSDecimalNumber(decimal: decimal).doubleValue, so that I could check the result with unit tests. Multiplying with the pow function introduces some tiny rounding differences which would normally not be an issue but which do not produce the bitwise-identical results I wanted.
An alternative way to use the exponent which does produce identical results to NSDecimalNumber is to multiply (or divide) by 10 in a loop:
let exp = Int(_exponent)
if exp > 0 {
for _ in 0..<exp {
result *= 10.0
}
} else if exp < 0 {
for _ in 0..<(-exp) {
result /= 10.0
}
}
Then adjust the result for negative values:
if _isNegative != 0 {
result = -result
}
There is one special value that should be handled: Decimal also has NaN (Not a Number) which should be mapped to Double.nan. I added this at the top of the function as well as a quick check for zero:
guard !isZero else { return .zero }
guard !isNaN else { return .nan }
Optimisations
While benchmarking I noticed that adding the isNaN check really affected performance. Internally, Decimal.nan is represented by _length of zero and _isNegative set. This is documented in a comment in NSDecimal.h.
Replacing the above guard statements made the function around twice as fast for smaller values:
guard _length != 0 else {
return _isNegative != 0 ? .nan : 0
}
I tried a few other tricks like a lookup table for powers of 10, but they either didn’t improve performance by much, or they introduced tiny rounding differences compared to converting via NSDecimalNumber.
With the NaN optimisation and casting the mantissa to two UInt64, here are the performance results for different classes of decimal value:
| Decimal class | NSDecimalNumber | Our conversion | Speedup |
|---|---|---|---|
| Small integers | 131 μs | 8.3 μs | 16× |
| Large integers | 143 μs | 8.1 μs | 18× |
| Currency values (2 dec.) | 140 μs | 8.3 μs | 17× |
| Small positive exponents | 138 μs | 9.7 μs | 14× |
| Small negative exponents | 162 μs | 14 μs | 12× |
| Large positive exponents | 265 μs | 80 μs | 3.3× |
| Large negative exponents | 620 μs | 253 μs | 2.5× |
| Random (mixed) | 375 μs | 148 μs | 2.5× |
Quite an impressive improvement! Most of this comes from not having to heap-allocate an NSDecimalNumber for the conversion. The large exponent values are slower because of the loop.
Here’s the final version, as an extension on Double:
extension Double {
init(_ decimal: Decimal) {
// Fast check for zero and NaN
guard decimal._length != 0 else {
self = decimal._isNegative != 0 ? .nan : 0
return
}
// Cast 8× UInt16 mantissa to 2× UInt64
var m = decimal._mantissa
let (low, high): (UInt64, UInt64) = withUnsafePointer(to: &m) {
$0.withMemoryRebound(to: UInt64.self, capacity: 2) {
($0[0], $0[1])
}
}
// Shift high int by 64 bits, add low int
var result = Double(high) * 0x1p64 + Double(low)
// Multiply or divide by exponent
let exp = Int(decimal._exponent)
if exp > 0 {
for _ in 0..<exp {
result *= 10.0
}
} else if exp < 0 {
for _ in 0..<(-exp) {
result /= 10.0
}
}
// Negate if needed
if decimal._isNegative != 0 {
result = -result
}
self = result
}
}
How about converting Decimal to an Int?
Extracting integer values
You might expect integers to be simpler than doubles but they actually have more edge cases to consider. With Double you can keep multiplying or dividing by 10 to shift by the exponent, but with Int you have to worry about overflows.
I found that it was easier to support extracting only whole values to eliminate any rounding complexity. If needed, values can be pre-rounded using Decimal.round().
The first part of extracting Int is almost identical to Double, except that NaN is not valid for ints and returns nil:
extension Int64 {
init?(exactly decimal: Decimal) {
guard decimal._length != 0 else {
guard decimal._isNegative == 0 else {
return nil // NaN
}
self = 0
return
}
var m = decimal._mantissa
let (low, high): (UInt64, UInt64) = withUnsafePointer(to: &m) {
$0.withMemoryRebound(to: UInt64.self, capacity: 2) {
($0[0], $0[1])
}
}
This next part looks similar to Double but with additional checks for int overflow. The first thing to check is if the high int is non-zero and fail otherwise. The reasoning is that if the unshifted value needs both UInt64 halves of the mantissa, then it’s very unlikely to fit in a single Int64 once shifted by the exponent. Technically it’s possible, but I’ll delve into that below.
// If high int is set then unlikely to fit in single Int64
guard high == 0 else {
return nil
}
var val = low
let exp = Int(decimal._exponent)
if exp > 0 {
var overflow = false
for _ in 0..<exp {
(val, overflow) = val.multipliedReportingOverflow(by: 10)
guard !overflow else { return nil }
}
} else if exp < 0 {
var remainder: UInt64 = 0
for _ in 0..<(-exp) {
(val, remainder) = val.quotientAndRemainder(dividingBy: 10)
guard remainder == 0 else { return nil }
}
}
For a positive exponent I shift the decimal place using a safe multiply. If I’d used val *= 10 then it would be easy to crash with an arithmetic overflow. When the exponent is negative I check that the value can be cleanly divided by 10. A remainder means the value can’t be represented by an integer, so return nil.
The rest of the function is also a little more complicated because I need to check if the UInt64 value overflows when converted to Int64. Another wrinkle is that -Int64.min doesn’t actually fit into an Int64 so that edge case has to be handled specially:
if decimal._isNegative == 0 {
guard let result = Int64(exactly: val) else { return nil }
self = result
} else if let positive = Int64(exactly: val) {
self = -positive
} else if val == UInt64(Int64.max) + 1 {
self = .min
} else {
return nil
}
}
}
So why did I return nil if the high int was non-zero earlier?
Compacted decimals
The one field of the Decimal struct listed above that I didn’t talk about is _isCompact. So what is this used for?
A Decimal can represent the number 123,000 in many different ways:
| Mantissa | Exponent |
|---|---|
| 123 | 3 |
| 1,230 | 2 |
| 12,300 | 1 |
| 123,000 | 0 |
| 1,230,000 | -1 |
| 12,300,000 | -2 |
These are all the exact same value, but if you print Decimal(123_000).exponent you’ll always get 3, as shown in the first row. This is because the “compact” representation is the one with no trailing zeroes on the mantissa.
The source for Decimal.compact() shows that it keeps dividing by 10 and increasing the exponent as far as possible, and then sets the _isCompact flag. Every time you create a Decimal from another numeric or string value it will call compact() before returning. Any mathematical operation will also return a compact value. It’s actually quite difficult to create a Decimal that isn’t compacted, but it is possible by manually specifying the mantissa and exponent.
So how does this help? It means that if I assume that any Decimal is already compacted then I don’t need to handle the negative exponent case, because any integer has already been shifted into the smallest mantissa possible. The whole if exp < 0 path can be removed and replaced with an early return nil instead. That’s why I also didn’t bother handling the “non-zero high int” scenario because that could never fit into a single Int64 with a compacted Decimal.
Just in case, an un-compacted decimal can be handled like this after the zero/NaN check:
var decimal = decimal
if decimal._isCompact == 0 {
NSDecimalCompact(&decimal)
}
Final thoughts
So was all that worth it? If I were only converting a couple of Decimal values, maybe not… I’d just hold my nose and convert via NSDecimalNumber 😁
For dealing with thousands of values though, a more than 10× speedup is nothing to sneeze at. Plus it was interesting to learn that Decimal is not so mysterious when you look inside: just a big integer and a power of ten. I should probably open a pull request to swift-foundation to finally add these conveniences.
Any comments or questions about this post? ✉️ nick @ this domain.
— Nick Randall