Skip to content
Advertisement

What can I do to output in MongoDB with $inc from always being decimal with 2 point accuracy? (rounding output)

So I’m using MongoDB 6.0 (and motor driver in python) and for example I have a code like that:

JavaScript

and assuming the current value of “balance” field in db is 5.91 the final value will be 0.9900000000000002, when I want it to be 0.99

What can I do, so mongodb will be automatically “rounding” this output to 2 point accuracy?

Advertisement

Answer

To preserve numeric fidelity for a financial application, you need to use the Decimal128 BSON type. This is supported in pymongo as follows:

JavaScript

prints:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement