Why do I get InvalidCastException when casting a double to decimal

旧城冷巷雨未停 提交于 2019-12-29 01:35:39

问题


I'm trying to debug an application which gets an InvalidCastException. The failing line is

decimal d = (decimal)row[denominator];

inspecting this in the debugger(see screenshot below), row[denominator] holds a double with value 8.0 as far as I can tell. Surly there shouldn't be any problem casting that to a decimal ?

(The 'row' type is from 3. party library, which again is filled from data from MySQL. The issue arised when testing against an older MySQL server which apparently returns some aggregates as double vs decimal on MySQL 5.1 - same query ,exact same copy of data in the database)

Visual Studio Screenshot http://img18.imageshack.us/img18/3897/invaldicast.png

Any help on how I could further investigate this ?


回答1:


Eric Lippert has blogged about exactly this in depth. I agree it's unintuitive at first, but he explains it well: Representation and Identity




回答2:


You need to cast it to a double first as row[denominator] is a double boxed as an object i.e.

decimal d = (decimal)((double)row[denominator]);



回答3:


I'd try

decimal d = Convert.ToDecimal(row[denominator]);

or

decimal d = 0;
if (!decimal.TryParse(row[denominator], out d))
    //do something



回答4:


You can use:

double d1 = (double)row[denominator];
decimal d = (decimal) d1;

Or, of course, shorten that to:

decimal d = (decimal) (double)(row[denominator]);

Because there is an unboxing step involved, you need 2 steps.




回答5:


A suggestion: try using Convert.ToDecimal() instead of direct casting.




回答6:


Try casting it to a double first. The row[denominator] is boxed, so a straight cast to decimal won't work.




回答7:


Judging from the error message and description I assume that row[denominator] is a boxed double, so of type object. Unboxing can only be done to the correct underlying datattype, since the runtime doesn't now where to find the actual conversion operator from double to decimal (in your case it tries to find an operator which converts object to decimal, but that one is an unboxing operator and the underlying type is not decimal. So the right way should be to convert first to double and then to decimal:

decimal d = (decimal)(double)row[denominator];



回答8:


just do

decimal d = Convert.ToDecimal(row[denominator]);

this way, you don't need to worry about all the casting problems.



来源:https://stackoverflow.com/questions/1667169/why-do-i-get-invalidcastexception-when-casting-a-double-to-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!