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:

money = 4.92
from_snowflake = "19251"

await db["bank"].update_one({"snowflake": str(from_snowflake)}, {"$inc": {"balance": -float(money)}})

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:

from pymongo import MongoClient
from bson.decimal128 import Decimal128

db = MongoClient()['mydatabase']
money = Decimal128('-4.92')
from_snowflake = "19251"
db["bank"].insert_one({"snowflake": from_snowflake, "balance": Decimal128('5.91')})
db["bank"].update_one({"snowflake": str(from_snowflake)}, {"$inc": {"balance": money}})
print(db["bank"].find_one({}, {'_id': 0}))

prints:

{'snowflake': '19251', 'balance': Decimal128('0.99')}
9 People found this is helpful
Advertisement