Decimal128
is a high-precision 128-bit decimal-based floating-point data type in MongoDB. It provides greater precision and a larger range for storing decimal numbers compared to other common floating-point data types like Double
.
To specify a Decimal128
value in MongoDB, use the $numberDecimal
keyword followed by the decimal value enclosed in quotes. Here's an example demonstrating the insertion of a decimal128 data type:
db.example.insertOne({
amount: {
$numberDecimal: '1234.567890123456789012345678901234',
},
});
Alternatively, with the help of the JavaScript BSON library, you can use the Decimal128.fromString()
function to create a Decimal128 value from a string:
const { Decimal128 } = require('bson');
const decimalValue = Decimal128.fromString(
'1234.567890123456789012345678901234'
);
db.example.insertOne({ amount: decimalValue });
Decimal128
data type, you may encounter rounding differences between MongoDB and other systems or libraries when performing calculations involving mixed data types. To mitigate this, ensure that all operands are converted to the same data type (preferably, Decimal128
) before performing calculations.