But we are having trouble with floating point arithmetic so we have to be more careful like this:
Here is a more complex example to get the ratio of two numbers as percentage to two decimal places:
There is no `$round` operator in MongoDB Aggregation Framework at the moment. It would probably be useful, but in the meanwhile, I thought I could show a trick that allows you to get the same result using just the supported math operators. Starting with very simple example  we enter floating point numbers and we want to truncate them to two decimal places: Note we're not actually rounding here, we are truncating to the desired decimal place. But we are having trouble with floating point arithmetic so we have to be more careful like this: Here is a more complex example to get the ratio of two numbers as percentage to two decimal places: And last, the example that got me to write this up  I was doing some aggregations of orders and line items and wanted to show the total price in thousands of dollars  but I wanted to round rather than truncating the amount:
3 Comments
d8a
8/15/2015 10:03:08 am
Funny thing, it did not work on number with all trailing zerors, like 57.0000000000
Reply
Prateek
5/2/2019 01:16:08 am
Below does not work for x<1.
Reply
Liviu
1/26/2023 12:25:24 am
Thank you kind sir for this, I am using mongo 4.0 and I can't upgrade to newer versions. This saved me!
Reply
Leave a Reply. 
Asya KamskyLikes technical puzzles, world travel and fancy food Archives
January 2020
Categories
All
