简体   繁体   中英

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 . You need to convert it to a double after first unboxing it. 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 . If you want to use a decimal, you should use 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 . By all means have one overload for double and one for decimal , but give them appropriate parameter types.

As an alternative to John's answer, if you want to use other number types than just decimal, you could use this code;

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

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