Problem with bson_append_double

17 views
Skip to first unread message

Thành Khắc Nguyễn

unread,
May 29, 2017, 2:54:37 AM5/29/17
to mongodb-user


Dear All!
When using function bson_append_double, i got this problem.
 
    bson_init(bson_doc);           
    double dvalue = 0.01;
    bson_append_double(pbson, "para.12.errSave", -1,dvalue);

But the result i got when printf is crazy long number  0.0099999999 ...

Did anyone face this problem before, and how to resolve this?
Thanks and Regard.



Sam Rossi

unread,
May 30, 2017, 12:21:55 PM5/30/17
to mongodb-user
Hi Thành! This looks like a general error relating to how most decimal numbers can't be represented exactly in floating point. A quick google leads to a number of great tutorials on the subject, but this one in particular looks like it might be instructive. The basic idea is that only fractions with a denominator of a power of 2 can be expressed exactly in floating point, so all other values are represented as the closest value that can be expressed.

Let me know if you have any other questions!

Sam Rossi

unread,
May 30, 2017, 12:50:43 PM5/30/17
to mongodb-user
I forgot to mention this, but if you need to exactly represent decimal values for some reason, you can also use the BSON decimal type rather than a floating point number. 
Reply all
Reply to author
Forward
0 new messages