简体   繁体   English

错误:将十进制转换为双精度时,指定的转换无效

[英]Error: Specified cast is not valid while converting decimal to double

I have a function as under 我有一个功能如下

private double RoundOff(object value)

    {
        return Math.Round((double)value, 2);
    }

And I am invoking it as under 而且我正在根据

decimal  dec = 32.464762931906M;
var res = RoundOff(dec);

I am gettingthe below error 我收到以下错误

Specified cast is not valid 指定的演员表无效

What is the mistake? 怎么了

Thanks 谢谢

Casting the object to double will attempt to unbox the object as a double, but the boxed object is a decimal . object强制转换为double会尝试将对象取消装箱为double,但是装箱的对象是decimal You need to convert it to a double after first unboxing it. 您需要先将其取消装箱后才能将其转换为double。 Then you perform the rounding: 然后执行四舍五入:

Math.Round((double)(decimal)value, 2);

The other answers are correct in terms of getting something that will run - but I wouldn't recommend using them. 就获得可以运行的东西而言,其他答案是正确的-但我不建议您使用它们。

You should almost never convert between decimal and double . 您几乎永远不要decimaldouble之间转换。 If you want to use a decimal, you should use Math.Round(decimal) . 如果要使用小数,则应使用Math.Round(decimal) Don't convert a decimal to double and round that - there could easily be nasty situations where that loses information. 请勿将小数转换为双精度并四舍五入-容易在讨厌的情况下丢失信息。

Pick the right representation and stick with it. 选择正确的表示形式并坚持下去。 Oh, and redesign RoundOff to not take object . 哦,重新设计RoundOff使其 RoundOff object By all means have one overload for double and one for decimal , but give them appropriate parameter types. 一定要对double有一个重载,对于decimal有一个重载,但要给它们适当的参数类型。

As an alternative to John's answer, if you want to use other number types than just decimal, you could use this code; 作为John答案的替代方法,如果您想使用除十进制以外的其他数字类型,则可以使用此代码;

    private double RoundOff(object value)
    {
        return Math.Round(Convert.ToDouble(value), 2);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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