Cannot implicitly convert type 'decimal' t

2020-04-18 05:47发布

问题:

I have this code in a shopping cart I am creating but I am receiving the error shown in the title.The error is showing up on this line:

回答1:

Just call ToString to get a string representation of the decimal value:

order.Total = orderTotal.ToString("G");

Although I don't see why you would store the member Total as a string and not as a decimal too.



回答2:

It sounds like the Order class has a Total property that's a string. Check the class definition for Order. If that's the case, I'd recommend changing the Total data type to a decimal, because having a currency value represented as a string doesn't make sense. decimal makes more sense.



回答3:

How is your Order class looks like ? What is the type of the Property called Total ? It looks like it is a string type. Here you are trying to set decimal value to a string type That is y you are getting that error. So you need to convert decimal to string before assigning it to a string varaiable. Use the toString() method.

order.Total = orderTotal.ToString();

As Tudor already mentioned, It is better to use Total as a decimal property as it will be easy for you to do all mathematical operations. You dont need to convert it to decimal format every time you want to do an arithmetical operation and convert it again back to string



回答4:

Change the type of Order.Total to Decimal. The data type Decimal does not automatically convert to string (and visa-versa) which is why you're getting an error, plus, any subsequent calls to Order.Total would be string related, so you would not be able to use operators like Order.Total +=

Also note that any binding convenience like a DataTable's 'format' property would be ignored because the underlying architecture won't call string.ToString(format).