0
votes

As I know, JavaScript uses IEEE 754 Floating point to treat real numbers. The problem arises when using it, it's quite common issue:

0.1 + 0.2 = 0.30000000000000004

Most of time, using the module like 'big.js', but the problem is when using MongoDB.

Look at this document:

{ "_id" : ObjectId("58ff8f721bbfbcd140e472b3"), "value" : 0.1 }

When I run $inc like this:

db.dec.update({ _id: ObjectId('58ff8f721bbfbcd140e472b3') }, { $inc: { value: 0.2 }});

The result is not good at all:

{ "_id" : ObjectId("58ff8f721bbfbcd140e472b3"), "value" : 0.30000000000000004 }

I know why it's happening, but is there a way to avoid this problem?

1
why is this a problem for you? - Thomas
@Thomas Because I'm handling the currency - modernator
To me this sounds like a matter of formatting, not a problem with the numeric system. Check this: var nr = .1 + .2; console.log(nr, nr.toLocaleString("en", {style: "currency", currency: "USD"})) Number#toLocaleString() - Thomas
the only point where these floating point errors actually are a problem, is when checking for equality (.1 + .2) === .3 - Thomas
@Thomas Okay, then how to use it in MongoDB query? Now I know what you are trying to say, but how put them in the query? - modernator

1 Answers

1
votes

If you know exactly the number of decimal places you want, you can do Number((.1+.2).toFixed(1)). Or you could use an orm for mongodb like mongoose, and define models for your database documents, and define the precision you want with some code in your model.