Double to Decimal without rounding after 15 digits

Saturday, July 5, 2014

When converting a "high" precision Double to a Decimal I loose precision with Convert.ToDecimal or casting to (Decimal) due to Rounding.

Example :

double d = -0.99999999999999956d;
decimal result = Convert.ToDecimal(d); // Result = -1
decimal result = (Decimal)(d); // Result = -1

The Decimal value returned by Convert.ToDecimal(double) contains a maximum of 15 significant digits. If the value parameter contains more than 15 significant digits, it is rounded using rounding to nearest.

So I in order to keep my precision, I have to convert my double to a String and then call Convert.ToDecimal(String):

decimal result = System.Convert.ToDecimal(d.ToString("G20")); // Result = -0.99999999999999956d

This method is working but I would like to avoid using a String variable in order to convert a Double to Decimal without rounding after 15 digits?