开发者

Noob Concern: Converting Dec to String C#

I am calling a method that returns a decimal, which I need to display in a textbox.

tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked); 

It's saying I can't implicitly convert dec to string...

So I tried two things (probably incorrectly)

tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString;
tbxDisplayCost.Text = (string)dinnerFun.Cal开发者_Go百科cTotalCost(cbxHealthy.Checked); 

Neither worked... and I'm kinda scratching my head to figure out how I can get that returned dec to be displayed in the textbox...


The first line is trying to use a method group (the name of the method without the brackets) - it's not calling the ToString method, which is what I suspect you intended. To do that you want:

tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString();

The second line is trying to just cast the value, which won't work as there's no explicit conversion from decimal to string either.

For clarity I'd quite possibly separate the "calculation" step from the "display" step:

decimal cost = dinnerFun.CalcTotalCost(cbxHealthy.Checked);
tbxDisplayCost.Text = cost.ToString();

Note that you might want to provide a numeric format specifier to ToString, e.g.

decimal cost = dinnerFun.CalcTotalCost(cbxHealthy.Checked);
tbxDisplayCost.Text = cost.ToString("c"); // Display as a currency value


So close:

tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString();

And if you don't like the format when it comes out, you can tweak things with a standard or custom format string argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜