[CSHARP-3416] Discrepanices between BsonDocument and json strings on double values Created: 09/Feb/21  Updated: 27/Oct/23  Resolved: 10/Feb/21

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: 2.10.4
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Jiaxing Song Assignee: Unassigned
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

.net framework 4.7.2


Case:

 Description   

var document = new BsonDocument {

{ "double1", 0.5710711036366942 }

,
{ "double2", 1.1897551732621 } ,
{ "double3", 1.680586318655911 } };

var jsonDoc = document.ToJson();
Console.WriteLine(jsonDoc);

 

This default extension methods ToJson will output:

{ "double1" : 0.57107110363669422, "double2" : 1.1897551732620999, "double3" : 1.6805863186559109 }

 

while insert this bson document into MongoDB won't introduce the discrepancy, the ToJson method will change the valid double values.  

1. Could this be resolved by customized IBsonSerializer or JsonWriterSettings?

2. Is it more reasonable to keep the same value in default ToJson() ?

 

Thanks for the time and efforts in advance.



 Comments   
Comment by Mikalai Mazurenka (Inactive) [ 02/Mar/21 ]

jiaxson@microsoft.com, it's not about MongoDB specific types but about C# literal types. Please see: Real literals

Comment by Jiaxing Song [ 22/Feb/21 ]

Hello @Mikalai Mazurenka

Thanks for your suggestions. Here my source data was json string, I didn't explicitly assign the type(double or decimal)

So does BsonDocument detect floating number as double by default? How do I change the default type to decmical?

Another confusion is  numbers like 1.1897551732621 should be double precesion but still have this discrepancy

 

Comment by Mikalai Mazurenka (Inactive) [ 10/Feb/21 ]

Hi jiaxson@microsoft.com,
Thank you for reporting this issue.
Essentially it boils down to representation of floating-point numbers (https://floating-point-gui.de/).
The discrepancy is not introduced when writing/reading the data in database because there's no conversion along the way.
You cannot change this behavior with custom IBsonSerializer or JsonWriterSettings
You can use decimal instead of double if you need to guarantee the round trip representation.

Generated at Wed Feb 07 21:45:13 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.