简体   繁体   中英

How do I convert a double value to a value of type decimal with a fixed number of decimal places in .NET

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

This is what you are looking for. Convert.ToDecimal converts a double into decimal Math.Round rounds your decimal to desired number of decimal places.

decimal DoubleToDecimal(double value, int numberOfDecimalPlaces)
{
    return Math.Round(Convert.ToDecimal(value), numberOfDecimalPlaces);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM