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.