DEV Community

Kn8
Kn8

Posted on

decimal128 vs double in MongoDB

When it comes to storing numbers in MongoDB, you've got two options: Decimal128 and Double. Think of Decimal128 like a fancy calculator with 34 decimal places of precision, perfect for financial and scientific calculations. Double, on the other hand, is like a regular calculator that's great for storing large range of numbers and doesn't require as much precision.

Let's say you're building a stock trading app. You'll want to use Decimal128 for storing the exact price of a stock to ensure accuracy for your users. But for storing the temperature in Celsius in a weather application, Double will be a better option as it's more efficient and doesn't require that level of precision.

Keep in mind, Decimal128 is not a native MongoDB data type, so you'll need to use a library like 'mongodb-decimal' to work with it. Double, however, is native to MongoDB, so no additional libraries are needed.

In short, Decimal128 is like a fancy calculator for precise calculations and Double is like a regular calculator for storing large range of numbers with less precision. Choose the one that best fits your needs and have fun!

Here are a few examples of how to use the Decimal128 data type in MongoDB:

Using the mongodb-decimal library:
You can use the mongodb-decimal library to work with Decimal128 data type in MongoDB. First, you need to install the library by running the following command:

npm install mongodb-decimal
Enter fullscreen mode Exit fullscreen mode

Then you can use it in your code like this:

const Decimal128 = require('mongodb-decimal');
const decimalValue = new Decimal128("123.45");
// insert into a collection
await collection.insertOne({ value: decimalValue });

// find and update
await collection.updateOne({}, { $set: { value: new Decimal128("999.99") } });
Enter fullscreen mode Exit fullscreen mode

Using the Decimal128 constructor:

const decimalValue = new Decimal128("123.45");

// insert into a collection
await collection.insertOne({ value: decimalValue });

// find and update
await collection.updateOne({}, { $set: { value: new Decimal128("999.99") } });
Using the Decimal128.fromString() method:
Copy code
const decimalValue = Decimal128.fromString("123.45");

// insert into a collection
await collection.insertOne({ value: decimalValue });

// find and update
await collection.updateOne({}, { $set: { value: Decimal128.fromString("999.99") } });
Enter fullscreen mode Exit fullscreen mode

In all the examples above, the decimalValue variable holds the Decimal128 value, which can be inserted or updated into a MongoDB collection.

Note that these are just examples and you should make sure to handle any errors and also use appropriate MongoDB driver version to use Decimal128.

Top comments (0)