简体   繁体   English

Noob关注:将Dec转换为字符串C#

[英]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... 就是说我不能将dec隐式转换为字符串...

So I tried two things (probably incorrectly) 所以我尝试了两件事(可能是错误的)

tbxDisplayCost.Text = dinnerFun.CalcTotalCost(cbxHealthy.Checked).ToString;
tbxDisplayCost.Text = (string)dinnerFun.CalcTotalCost(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... 都没有用...我有点想弄清楚如何才能将返回的dec显示在文本框中...

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. 第一行正在尝试使用方法组 (不带方括号的方法名称)-它没有调用 ToString方法,这是我怀疑的目的。 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. 第二行是试图只的价值,这将无法正常工作,有一个从没有明确的转换decimalstring无论是。

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 , eg 请注意,您可能想为ToString提供数字格式说明符 ,例如

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. 而且,如果您不喜欢这种格式出现的格式,则可以使用标准自定义格式字符串参数来进行调整。

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

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