Skip to content

Decimal to double conversion loses precision #72125

@dakersnar

Description

@dakersnar

Description

The current algorithm for casting a decimal to a double loses precision.

Reproduction Steps

Example

double doubleValue = 10000000000000.099609375;
Console.WriteLine("Expected Result:");
Console.WriteLine(doubleValue.ToString("G99")); // 10000000000000.099609375

decimal decimalValue = 10000000000000.099609375m;
double res =  (double)decimalValue;
Console.WriteLine("Casted Double From Literal Decimal:"); 
Console.WriteLine(res.ToString("G99")); // 10000000000000.09765625

string strDouble = doubleValue.ToString("G99");
decimal decimalValueParsed = decimal.Parse(strDouble, System.Globalization.NumberStyles.Float);
double res2 =  (double)decimalValueParsed;
Console.WriteLine("Casted Double From Parsed Decimal:"); 
Console.WriteLine(res2.ToString("G99")); // 10000000000000.09765625

Expected behavior

The above three prints should print the same value.

Actual behavior

There is a precision loss when casting from decimal to double. I included two methods of constructing the decimal to demonstrate that the behavior is specifically tied to the decimal -> double conversion, and not the construction of the decimal.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions