1.Insert
db.test.insert(
)
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
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