skip to content

How does BSON's decimal128 type lay out a number in its 16 bytes, and why do 2.00 and 2.0 differ?

level: middleimportance: should knowfreq 20%

answer

  1. sign, exponent, coefficient
  2. binary integer, not decimal digits
  3. exponent bias of 6176
  4. 34 digits, always 16 bytes
  5. trailing zeros are never dropped

basics

~20 s

BSON decimal128 stores IEEE 754-2008 128-bit decimal in 16 little-endian bytes: a sign bit, a 14-bit biased exponent and a binary integer coefficient. It never normalizes, so 2.00 is 200E-2 and 2.0 is 20E-1: equal values, different bytes.

solid answer

~40 s

`decimal128` has type code `\x13` and a fixed 16-byte value, the IEEE 754-2008 128-bit decimal format using the binary integer encoding, BID, in little-endian order. Read as a 128-bit number, it holds a sign bit, a 14-bit exponent biased by 6176, and a coefficient stored as an unsigned binary integer, up to 34 decimal digits. The value is coefficient times ten to the exponent. Nothing normalizes it, so `2.00` is stored as 200E-2 and `2.0` as 20E-1. They compare equal but differ in bytes, which preserves the precision that was written. A driver must reject a string that cannot be represented exactly, and every value costs 16 bytes, even zero.

code

plaintext · 5 lines
plaintext
0.001234       D2 04 00 00 00 00 00 00  00 00 00 00 00 00 34 30
0.00123400000  40 EF 5A 07 00 00 00 00  00 00 00 00 00 00 2A 30
1E+3           01 00 00 00 00 00 00 00  00 00 00 00 00 00 46 30
-0             00 00 00 00 00 00 00 00  00 00 00 00 00 00 40 B0
NaN            00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 7C

go deeper

for a junior

Remember the fixed 16 bytes, the 34 significant digits and the idea of coefficient times a power of ten, which is what keeps decimal fractions exact.

for a middle

Read a vector: split the 16 bytes into words, pull out sign, biased exponent and coefficient, and show why 2.00 and 2.0 compare equal yet differ in bytes.

for a senior

Point out where exactness can leak: conversion to native types, byte-level comparison of equal values, and the driver rules that turn inexact rounding into an error instead of quiet loss.

for a principal

Consider what a team standardizes around the format's limits: how values cross service boundaries, as strings or value objects, and who owns the rule on precision.

## The three fields **`decimal128`** is BSON type `\x13`. Its value is always 16 bytes, holding an IEEE 754-2008 128-bit **decimal floating point** number. The whole 128-bit value is little-endian, like BSON's other numeric types, so the most significant byte comes last in a hex dump. Read as a number, it has three fields: - **Sign**: the top bit. - **Exponent**: the next 14 bits, stored with a **bias** of 6176. A stored 6170 means an exponent of -6. - **Coefficient**: the remaining 113 bits, an unsigned binary integer. The value is `coefficient x 10^exponent`. IEEE 754-2008 allows two encodings of the coefficient, and the BSON specification requires the **binary integer decimal** form, BID, and not densely packed decimal, DPD. ## Reading a corpus vector Here is the corpus vector for `0.001234` under the key `d`, which has a coefficient of 1234 and an exponent of -6: ```plaintext 18 00 00 00 document length: 24 13 type code: decimal128 64 00 key "d" as a cstring D2 04 00 00 00 00 00 00 low 64 bits: 0x04D2 = 1234 00 00 00 00 00 00 34 30 high 64 bits: 0x3034000000000000 00 document terminator ``` The sum is 4 + 1 + 2 + 16 + 1 = 24. In the high word, `0x3034` is binary `0011 0000 0011 0100`. The first bit is the sign, 0. The next 14 bits are `0x181A`, which is 6170, and 6170 minus 6176 gives -6. ## Why 2.00 and 2.0 differ Decimal128 does **not normalize**. The specification says it directly: `2.00` is stored as 200E-2 and `2.0` as 20E-1, and the two compare equally while representing different ideas. The corpus has the same case in another pair: | Written as | Coefficient | Exponent | Last two bytes | |---|---|---|---| | `0.001234` | 1234 | -6 | `34 30` | | `0.00123400000` | 123400000 | -11 | `2A 30` | The trailing zeros are kept because they say how precisely the number was known. That has a consequence for anyone comparing raw bytes: equal decimal128 values can have different encodings, so a byte comparison is the wrong test of numeric equality. Zero also has many forms, and the sign is kept: the corpus gives `-0` a high byte of `B0` where `0` has `30`. ## What the range buys The 14-bit exponent stores -6176 up to +6111, and the coefficient holds 34 decimal digits. Together they reach `9.999999999999999999999999999999999E+6144`, with the smallest non-zero magnitude at `1E-6176`. The specification rounds this off as a maximum of about `10^6145`. The price is a fixed size: - The value is 16 bytes, whatever the number. `0` costs the same as a 34-digit price. - An element is 16 bytes plus one type byte plus the key and its NUL. - Non-finite values sit in the same 16 bytes. The corpus has NaN with `7C` as its top byte and Infinity with `78`. Whether that price is worth paying over a `double` is a data-modeling choice; the format only sets the cost. ## The rules a driver must follow The Decimal128 specification keeps the value exact on its way through a driver: 1. **Round only if exact.** A string with too many digits may be stored if the extra digits are zeros, but an inexact rounding must raise an error. The corpus turns a very long `1000...0` into `1.000000000000000000000000000000000E+999` because that loses nothing. 2. **Error on overflow and underflow.** Clamping, which adds zeros to the coefficient to bring the exponent into range, happens silently because the value does not change. 3. **No automatic native conversion.** By default a driver returns an immutable value object, because native decimal types often have a different precision. It must offer the value as a string. 4. **No operator overloading.** You convert explicitly, do the arithmetic, and build a new value. Extended JSON carries the value as text, `{"$numberDecimal": "0.00123400000"}`, in both canonical and relaxed modes, so a round trip through the string keeps the trailing zeros. The corpus does mark some values as lossy through that string, such as a negative NaN, a signaling NaN and a NaN with a payload, because they all print as `NaN`. The layout has one further corner. Apart from Infinity and NaN, a value whose two bits after the sign are both 1 arranges its bits differently, and its coefficient would need more than 34 digits. Such a value is an invalid representation, and the specification says it is treated as zero.

  • What is stored for a value with more than 34 significant digits?
    If the digits past the 34th are all zeros, the driver can drop them by raising the exponent, because the value stays exact. If any of them is non-zero, rounding would be inexact and the Decimal128 specification says the operation must raise an error. A conforming driver never silently loses digits.
  • Why does the specification refuse automatic conversion to a language's decimal type?
    Because native decimal types often have a different precision from decimal128, so conversion can lose data or change representation. A driver returns an immutable value object by default and must offer it as a string. A driver may let you configure a mapping to a native type, but it should warn clearly about the risk.

Two price tags reading 2.00 and 2.0 name the same price, yet one claims more precision than the other. Decimal128 stores the tag as written, which is why the two compare equal while their bytes differ.

  • Decimal128 stores the number as a string of decimal digits.
  • 2.00 and 2.0 are normalized to the same bytes before storage.
  • BSON decimal128 uses the densely packed decimal coefficient encoding.
  • A driver silently rounds a 35-digit value to fit in 34 digits.
  • A small decimal128 value takes fewer bytes than a large one.