以下是表单上的按钮。用户在小计文本框中输入美元金额,然后按计算按钮。然后,它计算折扣并在表单底部的文本框中显示发票总额。我们假设如果输入的小计金额为“ $”,则使用解析方法将条目转换为十进制。我的问题是关于数据类型的成功。我现在是Bool,因为它是1或0。
当我尝试构建表单时,出现以下错误:
错误1无法将类型'布尔'隐式转换为'十进制'
namespace InvoiceTotal
{
public partial class frmInvoiceTotal : Form
{
public frmInvoiceTotal()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal sucess = 0m;
decimal subtotal = Decimal.TryParse(txtSubtotal.Text, out sucess);
decimal discountPercent = .25m;
decimal discountAmount = Math.Round(subtotal * discountPercent,2);
decimal invoiceTotal = Math.Round(subtotal - discountAmount,2);
txtDiscountPercent.Text = discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString(); // ("c");
txtTotal.Text = invoiceTotal.ToString(); // ("c");
txtSubtotal.Focus();
}
我想我没有为变量“成功”声明正确的数据类型?如果有人可以帮助我指出正确的方向,我将不胜感激!
*错误1无法将类型'布尔'隐式转换为'十进制'
我在Windows 8.1机器上使用Visual Studio Professional 2012。
尽管其他答案都是正确的,但我想在此基础上进行扩展。使用该TryParse
方法的原因是,允许在输入无效的情况下更好地控制程序流程。换句话说,如果输入错误,您想怎么办:
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal subtotal;
if (!decimal.TryParse(txtSubtotal.Text, out subtotal))
{
//Display some warning to the user
MessageBox.Show(txtSubtotal.Text + " is not a valid number");
//don't continue processing input
return;
}
//input is good, continue processing
decimal discountPercent = .25m;
decimal discountAmount = Math.Round(subtotal * discountPercent,2);
decimal invoiceTotal = Math.Round(subtotal - discountAmount,2);
}
在某些情况下,如果日期不正确,则不必控制程序流,因为无论如何您都将引发异常。在这种情况下,您可以使用Decimal.Parse
which来抛出一个FormatException
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句