4

Say I have the following aggregation :

 db.a.aggregate(
   [
     { $project: {  total: { $multiply: [ 4533, 0.0001 ] } } }
   ]
)

The output of this aggregation is 0.45330000000000004 when it clearly should be 0.4533. Is this a bug in the aggregation framework?

Nabil
  • 121
  • 1
  • 11
  • No this is not a bug. this is how mongodb gives you. you can use toFixed after getting value in nodejs. or you can use this https://github.com/debitoor/mongo-round – Dinesh undefined Jun 19 '17 at 09:52
  • 2
    [Welcome to computer science](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). Use [`$trunc`](https://docs.mongodb.com/manual/reference/operator/aggregation/trunc/) if you want something different. – Neil Lunn Jun 19 '17 at 09:53
  • See also: [MongoDB - What about Decimal type of value?](https://stackoverflow.com/questions/11541939/mongodb-what-about-decimal-type-of-value/11542549#11542549) – Neil Lunn Jun 19 '17 at 10:02
  • What I want to do is to round a number say 0.453334 to 4 decimals after the dot using only the aggregation framework. $trunc will truncate the number to its integer so it won't work for my case. – Nabil Jun 19 '17 at 10:06

1 Answers1

2

Okay then I was going to suggest multiplying and using $trunc, but you can basically get away with just chaining $multiply and $divide here:

db.a.aggregate(
   [
     { "$project": {  
       "total": {
         "$divide": [ 
           { "$multiply": [
             { "$multiply": [ 4533, 0.0001 ] },
              10000
           ]},
           10000
         ]
       } 
     }}
   ]
)

or just $divide when that is what you mean:

db.a.aggregate([
  { "$project": { "total": { "$divide": [ 4533, 10000 ] } } }
])

Which both will give you:

{  "total" : 0.4533 }

As noted, There is nothing new about floating point math and rounding, and as a general course you should avoid usage and simply apply the "non-floating point" version of what you actually mean.

The long read if you have a while is at What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317