diff --git a/src/MongoDB.Bson/ObjectModel/Decimal128.cs b/src/MongoDB.Bson/ObjectModel/Decimal128.cs index 0853fdf99e1..4b8d8091ce2 100644 --- a/src/MongoDB.Bson/ObjectModel/Decimal128.cs +++ b/src/MongoDB.Bson/ObjectModel/Decimal128.cs @@ -741,6 +741,16 @@ public static decimal ToDecimal(Decimal128 d) { if (Flags.IsFirstForm(d._highBits)) { + // fix for CSHARP-5792, make sure that Decimal128.MaxValue and MinValue are mapped back to + // decimal.MaxValue and MinValue. + if (d == Decimal128.MaxValue) + { + return decimal.MaxValue; + } + if (d == Decimal128.MinValue) + { + return decimal.MinValue; + } if (Decimal128.Compare(d, __minDecimalValue) < 0 || Decimal128.Compare(d, __maxDecimalValue) > 0) { throw new OverflowException("Value is too large or too small to be converted to a Decimal."); diff --git a/tests/MongoDB.Bson.Tests/ObjectModel/Decimal128Tests.cs b/tests/MongoDB.Bson.Tests/ObjectModel/Decimal128Tests.cs index 10cd3c5aa52..5b8b1a6c665 100644 --- a/tests/MongoDB.Bson.Tests/ObjectModel/Decimal128Tests.cs +++ b/tests/MongoDB.Bson.Tests/ObjectModel/Decimal128Tests.cs @@ -76,6 +76,8 @@ public void Decimal(string valueString, string expectedResult) [InlineData("1E-99", "0")] [InlineData("1E-6111", "0")] [InlineData("10000.0000000000000000000000001", "10000.000000000000000000000000")] // see: CSHARP-2001 + [InlineData("9999999999999999999999999999999999E+6111", "79228162514264337593543950335")] // see: CSHARP-5792 + [InlineData("-9999999999999999999999999999999999E+6111", "-79228162514264337593543950335")] public void ToDecimal_should_return_expected_result(string valueString, string expectedResultString) { var subject = Decimal128.Parse(valueString); diff --git a/tests/MongoDB.Bson.Tests/Serialization/Options/RepresentationConverterTests.cs b/tests/MongoDB.Bson.Tests/Serialization/Options/RepresentationConverterTests.cs index 0bed83d83e3..6548744f0e9 100644 --- a/tests/MongoDB.Bson.Tests/Serialization/Options/RepresentationConverterTests.cs +++ b/tests/MongoDB.Bson.Tests/Serialization/Options/RepresentationConverterTests.cs @@ -119,6 +119,16 @@ public void TestConversions() Assert.Equal((long)(ulong)int.MaxValue, converter.ToInt64(int.MaxValue)); Assert.Equal(1UL, converter.ToUInt64((long)1)); Assert.Equal((long)(ulong)long.MaxValue, converter.ToInt64(long.MaxValue)); + + // general decimal <-> Decimal128 checks + Assert.Equal(123.45m, converter.ToDecimal(new Decimal128(123.45m))); + Assert.Equal(-123.45m, converter.ToDecimal(new Decimal128(-123.45m))); + + // System.Decimal should be mapped to Decimal128.MaxValue and vice versa + Assert.Equal(Decimal128.MaxValue, converter.ToDecimal128(decimal.MaxValue)); + Assert.Equal(Decimal128.MinValue, converter.ToDecimal128(decimal.MinValue)); + Assert.Equal(decimal.MaxValue, converter.ToDecimal(Decimal128.MaxValue)); + Assert.Equal(decimal.MinValue, converter.ToDecimal(Decimal128.MinValue)); } [Theory]