PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

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

 October 24, 2022     bson, decimal, mongodb, pymongo, python     No comments   

Issue

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?


Solution

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')}


Answered By - Belly Buster
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing