What is Decimal128 in MongoDB: Explanation and Usage
decimal128 in MongoDB is a data type that stores high-precision decimal numbers using 128 bits. It is designed to handle exact decimal values, such as currency, without rounding errors common in floating-point types.How It Works
decimal128 stores numbers with very high precision and a fixed decimal point, unlike regular floating-point numbers that can lose accuracy. Think of it like a super-accurate calculator that remembers every decimal place exactly, which is important for money or measurements.
It uses 128 bits (16 bytes) to represent the number, allowing it to hold very large or very small decimal values precisely. This avoids rounding errors you might see with double types, which are binary floating-point numbers.
In MongoDB, decimal128 is supported natively and can be used to store and query exact decimal values safely.
Example
This example shows how to insert and retrieve a decimal128 value in MongoDB using the Node.js driver.
const { MongoClient, Decimal128 } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); await client.connect(); const db = client.db('testdb'); const collection = db.collection('prices'); // Insert a decimal128 value await collection.insertOne({ price: Decimal128.fromString('19.99') }); // Find and print the value const doc = await collection.findOne({}); console.log('Stored price:', doc.price.toString()); await client.close(); } run();
When to Use
Use decimal128 when you need to store exact decimal numbers without rounding errors. This is especially important for financial data like prices, interest rates, or currency conversions where precision matters.
It is also useful in scientific calculations or measurements where exact decimal representation is required.
If you use floating-point types like double, small rounding errors can accumulate and cause incorrect results, so decimal128 helps avoid that.
Key Points
decimal128stores decimal numbers with high precision using 128 bits.- It avoids rounding errors common in floating-point types.
- Ideal for financial and scientific data requiring exact decimal values.
- Supported natively in MongoDB and its drivers.
Key Takeaways
decimal128 stores exact decimal numbers with high precision in MongoDB.double.decimal128 for easy insertion and querying.