Mongodb multiplication multiplication operator

Let's say I have the following aggregation:

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

      

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

+3


source to share


1 answer


Well, then I was going to propose to multiply and use $trunc

, but you can basically get away with just a chain $multiply

and $divide

here:

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

      

or simply $divide

, if this is what you mean:

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

      



What will both give you:

{  "total" : 0.4533 }

      

As noted, there is nothing new about math and floating point rounding, and as a general guideline, you should avoid using and just apply the "non-floating point" version of what you actually mean.

A long read, if you have time, is on What Every Computer Scientist Should Know About Floating Point Arithmetic .

0


source







All Articles