Cannot implicitly convert type 'decimal' t

2020-04-18 05:43发布

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:

4条回答
Summer. ? 凉城
2楼-- · 2020-04-18 06:25

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楼-- · 2020-04-18 06:27

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).

查看更多
Fickle 薄情
4楼-- · 2020-04-18 06:33

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

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-04-18 06:39

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.

查看更多
登录 后发表回答