[CSHARP-2210] System.Decimal is serialized as a string by default Created: 08/Mar/18  Updated: 09/Jan/24  Resolved: 08/Mar/18

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: 2.5
Fix Version/s: 3.0.0

Type: Task Priority: Minor - P4
Reporter: Yaroslav Vishnevsky Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: PNG File screenshot-1.png    
Issue Links:
Related
related to CSHARP-2217 System.Decimal support in FilterDefin... Closed
Epic Link: Implement 3.0 release
Quarter: FY24Q3
Documentation Changes Summary:

1. What would you like to communicate to the user about this feature?
2. Would you like the user to see examples of the syntax and/or executable code and its output?
3. Which versions of the driver/connector does this apply to?


 Description   

ToBsonDocument() extension method serialize decimal as String

decimal pi = 13.14m;
           await new MongoClient()
                .GetDatabase("TestDb")
                .GetCollection<BsonDocument>("TestCollection")
                .InsertManyAsync(new[] { new TestClass { DecimalValueC = pi }.ToBsonDocument(), new { DecimalValueA = pi }.ToBsonDocument() } );



 Comments   
Comment by Robert Stam [ 08/Mar/18 ]

Values of type System.Decimal are serialized as strings for two reasons:

1. The range of System.Decimal is different from that of BSON Decimal128 so overflow or loss of precision is possible
2. For backward compatibility (the driver has been serializing System.Decimal as string since before the BSON Decimal128 type was introduced)

If you want to configure your application to serialize System.Decimal as BSON Decimal128 you can do so by adding the following configuration code to your application:

var decimalSerializer = new DecimalSerializer(BsonType.Decimal128, new RepresentationConverter(allowOverflow: false, allowTruncation: false));
BsonSerializer.RegisterSerializer(decimalSerializer);

You must register this serializer as early as possible. At a minimum it must be registered before any System.Decimal values are serialized.

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