[CSHARP-1979] Math.Round doesn't work anymore with MongoDB Created: 07/May/17  Updated: 27/Oct/23  Resolved: 16/May/17

Status: Closed
Project: C# Driver
Component/s: Serialization
Affects Version/s: 2.4.3
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Luc Begnoche Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: Bug
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

x64


Issue Links:
Related
is related to CSHARP-1858 Add user configurable output converte... Closed
Backwards Compatibility: Fully Compatible

 Description   

The following fix broke an important feature of rounding Double to a few digits.

Commit : d918bb829beafa619db061394ce183f00619b880
Issue : CSHARP-1731: Use "G17" instead of "R" when converting Double to Strin...

The standard C# Double.ToString() method serializes 15 digits instead of 17 and this is on purpose. It allows approximation to look like an exact number. For instance, 7.33 is stored as
7.3300000000000001. Using G17 instead of R prohibit using Math.Round to output a JSON document that contains "7.33".

Sample Code:
Double d1 = 7.33333333333;
Double d2 = Math.Round(d1, 2);
BsonValue v2 = d2;
String s2 = v2.ToString();

The main problem for me is when I consume the JSON document in JavaScript with Meteor on the website. I need again to round in JavaScript. Would that be possible to at least provide an option or another class like BsonDoubleR that would allow to control the desired behavior. That was working before I upgraded the driver for MongoDB 3.4 support.



 Comments   
Comment by Robert Stam [ 16/May/17 ]

Closing this ticket because the desired behavior can eventually be accomplished using the changes implemented in CSHARP-1858.

Comment by Robert Stam [ 16/May/17 ]

This isn't really related to Math.Round, which simply maps one double value to another double value.

It is related to how double values are serialized to JSON.

CSHARP-1731 was implemented because in most cases it is more important to preserve precision. Users rarely want to lose precision!

When CSHARP-1858 is implemented (probably in version 2.5) you will be able to register your own DoubleJsonConverter that can use whatever output precision you want to have.

Comment by Luc Begnoche [ 09/May/17 ]

Using MongoDB C# Driver 2.4.3 with a MongoDB 3.0 server fixes the problem temporarily. Somehow the value is stored in MongoDB server correctly, looking like 7.33 instead of 7.3300000000000001

I'll update again when I upgrade the MongoDB server to 3.4

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