So I’m using MongoDB 6.0 (and motor driver in python) and for example I have a code like that:
JavaScript
x
5
1
money = 4.92
2
from_snowflake = "19251"
3
4
await db["bank"].update_one({"snowflake": str(from_snowflake)}, {"$inc": {"balance": -float(money)}})
5
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
1
10
10
1
from pymongo import MongoClient
2
from bson.decimal128 import Decimal128
3
4
db = MongoClient()['mydatabase']
5
money = Decimal128('-4.92')
6
from_snowflake = "19251"
7
db["bank"].insert_one({"snowflake": from_snowflake, "balance": Decimal128('5.91')})
8
db["bank"].update_one({"snowflake": str(from_snowflake)}, {"$inc": {"balance": money}})
9
print(db["bank"].find_one({}, {'_id': 0}))
10
prints:
JavaScript
1
2
1
{'snowflake': '19251', 'balance': Decimal128('0.99')}
2