Ittikorn S.
Ittikorn S.

Reputation: 288

Mongo $toDecimal rounded up number in aggregator

Schema

amount: Number

Input Data

{ amount: 1407633616694783200000 }

Since the schema is a number it will be stored as

{ amount: 1.4076336166947832e+21 }

When I try to do the aggregator with this query

'$project': {
  'amount': {
    '$toDecimal': '$amount'
   }
 }

The result return

{ amount: 1.40763361669478E+21 }

The difference between those two values is 3200000

What happened here? Why mongo is showing different numbers and how to solve this because when I try to add or subtract it with another number. The result is not summed up incorrectly.

Playground

Upvotes: 1

Views: 412

Answers (1)

felix
felix

Reputation: 9285

The problem comes from the double BSON type, which is used to store the amount here

From mongodb numeric decimal:

The decimal BSON type uses the IEEE 754 decimal128 decimal-based floating-point numbering format. Unlike binary-based floating-point formats (i.e., the double BSON type), decimal128 does not approximate decimal values and is able to provide the exact precision required for working with monetary data.

So if you need exact precision, use NumberDecimal("1407633616694783200000")

see the updated playground

Upvotes: 1

Related Questions