[CSHARP-2001] Decimal128.ToDecimal should not throw an exception when the conversion can succeed with a loss of precision Created: 13/Jun/17  Updated: 28/Oct/23  Resolved: 22/Sep/17

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: 2.4.4
Fix Version/s: 2.5

Type: Bug Priority: Major - P3
Reporter: Ryan Lawrence Assignee: Robert Stam
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Win10


Issue Links:
Duplicate
is duplicated by CSHARP-2098 Decimal128.Compare() gives inaccurate... Closed

 Description   

The following causes an overflow error:

var strValue = "10000.0000000000000000000000001";
Decimal128 decimal128Value;
Decimal128.TryParse( strValue, out decimal128Value );
var decimalValue = Decimal128.ToDecimal( decimal128Value );

Not that converting to double does not overflow:

var doubleValue = Decimal128.ToDouble( decimal128Value );

It is unclear why the Decimal128 value offers different precision than a standard .NET decimal. However the conversion to the .NET decimal should allow for a truncation of precision if necessary, as there currently is no other safe way to convert to decimal without going through some other type first (string or double).



 Comments   
Comment by Githook User [ 22/Sep/17 ]

Author:

{'email': 'robert@robertstam.org', 'name': 'rstam', 'username': 'rstam'}

Message: CSHARP-2001: Decimal128.ToDecimal should not throw when when the conversion can succeed with a loss of precision.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/0eae9257fbfd9f2eea93cb08deef8b19762f46d4

Comment by Robert Stam [ 15/Jun/17 ]

The .NET Decimal type is slightly different than the IEEE Decimal128 type. It has a smaller range and less precision.

Your are correct though that ToDecimal should not throw in this case. It should simply lose a bit of precision and return the closest Decimal it can.

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