When converting a "high" precision Double to a Decimal I lose 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?
d? I can offer some lightweight solutions in pseudocode (I'm not familiar enough with C# to write them in C#) if you know thatdis in a range like [-2..2] - Pascal Cuoqdoublecoming from somewhere else that you can't change? If it's declared as a decimal from the get-go (decimal d = -0.99999999999999956m;) it maintains that precision. - Chris SinclairConvert.ToDecimalsays "The Decimal value returned by this method contains a maximum of 15 significant digits. If the value parameter contains more than 15 significant digits, it is rounded using rounding to nearest." - Matthew Strawbridge