$inc generating some wrong value when incremented with negative decimal value

652 views
Skip to first unread message

Suraj Sawant

unread,
Jun 16, 2017, 2:58:17 AM6/16/17
to mongodb-user
While using $inc to decrement a value by some fractional value,ganerated output differs with expected output.

Steps to reproduce:

1.Insert
db.test.insert(

{"qty":4.464}

)

2.check results
db.test.find()

3.increment the value with negative fractional value
db.test.update({},{$inc:{"qty":-0.608}})

4.check the output
db.test.find()

Actual Output: "qty" : 3.8560000000000003
Expected Output: "qty" : 3.856

Kevin Adistambha

unread,
Jun 18, 2017, 8:20:30 PM6/18/17
to mongodb-user

Hi Suraj

While using $inc to decrement a value by some fractional value,ganerated output differs with expected output.

This is because MongoDB is using the industry-standard IEEE-754 floating point format. In short, this is not an error, but an unfortunate side-effect of conversion between base-2 to base-10 number.

If you need to be more precise, you can use the NumberDecimal representation which is available in MongoDB 3.4:

> db.test.insert({qty:NumberDecimal("4.464")})
WriteResult({ "nInserted" : 1 })

> db.test.update({},{$inc:{qty:-0.608}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.test.find()
{ "_id" : ObjectId("594718906f3f680c053aeec3"), "qty" : NumberDecimal("3.856000000000000") }

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages