[CSHARP-2582] Decimal128 to decimal conversion loses precision for zero Created: 10/Apr/19  Updated: 28/Oct/23  Resolved: 02/May/19

Status: Closed
Project: C# Driver
Component/s: BSON
Affects Version/s: 2.8.0
Fix Version/s: 2.8.1

Type: Bug Priority: Major - P3
Reporter: Thomas Hjorslev Assignee: Dmitry Lukyanov (Inactive)
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 10, dotnet core 2.1



 Description   

When converting a decimal to Decimal128 and back, the result is not as expected when the original decimal is "zero with decimals", e.g. 0.000

Code to reproduce:

var originals = new[] { 1M, 1.000M, 0M, 0.000M };
foreach( var original in originals )
{
    var dec128 = new Decimal128( original );
    var newDecimal = Decimal128.ToDecimal( dec128 );
    if( !decimal.GetBits( original ).SequenceEqual( decimal.GetBits( newDecimal ) ) )
        Console.Write( "!" );
    Console.WriteLine( $"{original} = {dec128} = {newDecimal}" );
}

The last value, 0.000M is converted to a straight Decimal.Zero.

I think this is due to line 719 in Decimal128.cs:

 if (Decimal128.IsZero(d))
{
    return decimal.Zero;
}

I don't believe this is the correct behavior.



 Comments   
Comment by Githook User [ 03/May/19 ]

Author:

{'name': 'Dmitry Lukyanov', 'username': 'DmitryLukyanov', 'email': 'dmitry.lukyanov@mongodb.com'}

Message: CSHARP-2582: Decimal128 to decimal conversion loses precision for zero.
Branch: v2.8.x
https://github.com/mongodb/mongo-csharp-driver/commit/6d9b44d24b9d1840ea613c772d11cb1d40dd1abb

Comment by Githook User [ 02/May/19 ]

Author:

{'name': 'Dmitry Lukyanov', 'username': 'DmitryLukyanov', 'email': 'dmitry.lukyanov@mongodb.com'}

Message: CSHARP-2582: Decimal128 to decimal conversion loses precision for zero.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/6e49826c642c426ff7e3170d0cccee32e636ac0c

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