In .NET, I have a value in a double variable that I need to convert to decimal with a specified number of decimal places, rounding as needed. The answer I am looking for would have a prototype something like this:
decimal DoubleToDecimal(double value, int numberOfDecimalPlaces)
The best I have been able to come up with converts the double to a string with the correct number of decimal places, and then parses it back into a decimal:
return decimal.Parse(
double.ToString("0." + new string(numberOfDecimalPlaces,'0'))
);
I would prefer a way that doesn't involve the conversion to/from string, as that seems quite inefficient.
decimal DoubleToDecimal(double value, int numberOfDecimalPlaces){
return Math.Round((decimal)value, numberOfDecimalPlaces);
}
If you need to preserve trailing zeroes try using this:
Math.Round((decimal)value,numberOfDecimalPlaces)+(0M*((decimal)Math.Pow(10,-numberOfDecimalPlaces)))
see:
> Math.Round(dd,20)
3.2222222
> (0M*((decimal)Math.Pow(10,-20)))
0.00000000000000000000
> Math.Round(dd,20)+(0M*((decimal)Math.Pow(10,-20)))
3.22222220000000000000