Cast a Double Variable to Decimal

后端 未结 5 733
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 02:22

How does one cast a double to decimal which is used when doing currency development. Where does the M go?

decimal dtot          


        
相关标签:
5条回答
  • 2020-12-15 02:44

    You only use the M for a numeric literal, when you cast it's just:

    decimal dtot = (decimal)doubleTotal;
    

    Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal you may get rounding errors. You may want to convert the numbers to Decimal before adding them together, or make sure that the numbers aren't floating point numbers in the first place.

    0 讨论(0)
  • 2020-12-15 02:45

    use default convertation class: Convert.ToDecimal(Double)

    0 讨论(0)
  • 2020-12-15 02:48
    Convert.ToDecimal(the double you are trying to convert);
    
    0 讨论(0)
  • 2020-12-15 03:04

    You can cast a double to a decimal like this, without needing the M literal suffix:

    double dbl = 1.2345D;
    decimal dec = (decimal) dbl;
    

    You should use the M when declaring a new literal decimal value:

    decimal dec = 123.45M;
    

    (Without the M, 123.45 is treated as a double and will not compile.)

    0 讨论(0)
  • 2020-12-15 03:05

    Well this is an old question and I indeed made use of some of the answers shown here. Nevertheless, in my particular scenario it was possible that the double value that I wanted to convert to decimal was often bigger than decimal.MaxValue. So, instead of handling exceptions I wrote this extension method:

        public static decimal ToDecimal(this double @double) => 
            @double > (double) decimal.MaxValue ? decimal.MaxValue : (decimal) @double;
    

    The above approach works if you do not want to bother handling overflow exceptions and if such a thing happen you want just to keep the max possible value(my case), but I am aware that for many other scenarios this would not be the expected behavior and may be the exception handling will be needed.

    0 讨论(0)
提交回复
热议问题