Quick Start: BSON Data Types - Decimal128
Rate this quickstart
Think back to when you were first introduced to the concept of decimals in numerical calculations. Doing math problems along the lines of 3.231 / 1.28 caused problems when starting out because 1.28 doesn't go into 3.231 evenly. This causes a long string of numbers to be created to provide a more precise answer. In programming languages, we must choose which number format is correct depending on the amount of precision we need. When one needs high precision when working with , the
decimal128is the one to use.
As the name suggests, decimal128 provides 128 bits of decimal representation for storing really big (or really small) numbers when rounding decimals exactly is important. Decimal128 supports 34 decimal digits of precision, or along with an exponent range of -6143 to +6144. The significand is not normalized in the decimal128 standard allowing for multiple possible representations: 10 x 10^-1 = 1 x 10^0 = .1 x 10^1 = .01 x 10^2 and so on. Having the ability to store maximum and minimum values in the order of 10^6144 and 10^-6143, respectively, allows for a lot of precision.
Sometimes when doing mathematical calculations in a programmatic way, results are unexpected. For example in Node.js:
This issue is not unique to Node.js, in Java:
Produces an output of:
The same computations in Python, Ruby, Rust, and others produce the same results. What's going on here? Are these languages just bad at math? Not really, binary floating-point numbers just aren't great at representing base 10 values. For example, the
0.1used in the above examples is represented in binary as
Passing in the decimal value as a string, the value gets stored in the database as:
If values are passed in as
Loss of precision can occur in the database:
Another consideration, beyond simply the usage in MongoDB, is the usage and support your programming has for decimal128. Many languages don't natively support this feature and will require a plugin or additional package to get the functionality. Some examples...
decimal128field came about in August 2009 as part of the revision of floating points. MongoDB 3.4 is when support for decimal128 first appeared and to use the
decimaldata type with MongoDB, you'll want to make sure you version that supports this great feature. Decimal128 is great for huge (or very tiny) numbers and for when precision in those numbers is important.