When going from a double to a decimal, presuming my double
can be represented as a decimal
...
Is it more appropriate to cast a double as a decimal:
(Explicit Numeric Conversions Table) (Note that this entry erroneously contradicts the former!)
double foo = bar; decimal foobar = (decimal)foo;
Or is it more appropriate to call the decimal
constructor:
(Decimal Constructor)
double foo = bar; decimal foobar = new decimal(foo);
I tend to use the decimal
constructor, but I wonder reasons to use one versus the other.
From what I can tell the only difference is that an explicit cast of a double below Decimal.MinValue
returns a zero, while using the constructor throws an OverflowException
EDIT: @Joren in the comments below notes that the cast throws an OverflowException
for small values as well... so apparently the MSDN documentation is incorrect.
Related Questions:
- C# cast a double variable to decimal
- Automatically cast from double to decimal safely: Is the following safe?
Use double for non-integer math where the most precise answer isn't necessary. Use decimal for non-integer math where precision is needed (e.g. money and currency). Use int by default for any integer-based operations that can use that type, as it will be more performant than short or long .
decimal dtot = (decimal)(doubleTotal);
Double uses 64 bits to represent data. Decimal uses 128 bits to represent data.
double for when you need relative accuracy (i.e. losing precision in the trailing digits on large values is not a problem) across wildly different magnitudes - double covers more than 10^(+/-300). Scientific calculations are the best example here.
There's really no difference. Using ILSpy:
// decimal public static explicit operator decimal(double value) { return new decimal(value); }
Based on examining the IL with LINQPad, the operator overload is called the same way in checked and unchecked contexts in C#.
In Visual Basic, CDec([double]) and CType([double],Decimal) calls the constructor directly, so there's no difference in that regard, but the cast is more able to participate in compile-time constant-folding than the constructor.
I would rather go for the constructor then! At least you get informed that your value is out of limits instead of setting it to 0 silently! The documentation says:
The explicit numeric conversion may cause loss of precision or result in throwing exceptions.
If one does not really care about precision than casting can be used. In the other hand, if you are playing with money for example, the last thing you would do is rounding off doubles! You don't want your application to turn valuable decimal fractions to 0 where you do not expect it to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With