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:
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: