C# 在C中验证tip计算器中的数据#

C# 在C中验证tip计算器中的数据#,c#,C#,当你没有在框中输入数字或字母时,你会看到一个弹出框,上面写着“请输入你的号码” //converted a textbox into a decimal Decimal enterNumber = Convert.ToDecimal(txtUserInput.Text); // as well as vaidate the data if (enterNumber<=0) { MessageBox.Show("Please enter your number"); } 我认为一个

当你没有在框中输入数字或字母时,你会看到一个弹出框,上面写着“请输入你的号码”

//converted a textbox into a decimal
Decimal enterNumber = Convert.ToDecimal(txtUserInput.Text);
// as well as vaidate the data
if (enterNumber<=0) {
    MessageBox.Show("Please enter your number");
}

我认为一个标准的方法是只使用,对货币进行重载。通过这种方式,您可以在所需的区域性中检查有效的货币输入

将数字的字符串表示形式转换为十进制 使用指定的样式和区域性特定格式的等效项。A. 返回值指示转换是成功还是失败

参数

  • s
    Type:System.String
    要转换的数字的字符串表示形式
  • style
    Type:System.Globalization.numberstyle
    枚举值的按位组合,指示允许的s格式。要指定的典型值是数字
  • provider
    Type:System.IFormatProvider
    提供有关s的区域性特定解析信息的对象
  • 结果
    Type:System.Decimal
    此方法返回时,如果转换成功,则包含与s中包含的数值相等的十进制数,如果转换失败,则为零。如果s参数为null或String.Empty、格式不符合样式或表示小于MinValue或大于MaxValue的数字,则转换失败。此参数未初始化地传递;结果中最初提供的任何值都将被覆盖
  • 如果s成功转换,则返回值
    Type:System.Boolean
    true;否则,错误
Exmaple

// Parse currency value using en-GB culture.
value = "£1,097.63";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = CultureInfo.CreateSpecificCulture("en-GB");
if (Decimal.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);

您还可以使用try-catch语句来查找正确类型的输入,从而简单地完成任务

public static bool TryParse(
    string s,
    NumberStyles style,
    IFormatProvider provider,
    out decimal result
)
// Parse currency value using en-GB culture.
value = "£1,097.63";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
culture = CultureInfo.CreateSpecificCulture("en-GB");
if (Decimal.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);