我试图找到当您不在框中输入数字或字母时,您会看到一个弹出框,显示“请输入您的号码”。
//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");
}
好吧,当我尝试 tryParse 时,我收到返回类型错误,不确定 return 关键字后面不能跟对象意味着什么
decimal filler = 0m;
if (Decimal.TryParse(txtUserInput.Text, out filler))
{
//error
return true;
}
// needs an else statment
else {
MessageBox.Show("needs to be a number");
txtUserInput.Focus();
//error
return false;
}
最佳答案
我认为标准方法是使用 decimal.TryParse
货币重载。这样您就可以检查所需文化中的有效货币输入
Converts the string representation of a number to its Decimal equivalent using the specified style and culture-specific format. A return value indicates whether the conversion succeeded or failed.
public static bool TryParse(
string s,
NumberStyles style,
IFormatProvider provider,
out decimal result
)
参数
- s
类型:System.String
要转换的数字的字符串表示形式。 - style
类型:System.Globalization.NumberStyles
枚举值的按位组合,指示 s 的允许格式。要指定的典型值是 Number。 - provider
类型:System.IFormatProvider
提供有关 s 的区域性特定解析信息的对象。 - result
类型:System.Decimal
当此方法返回时,如果转换成功,则包含与 s 中包含的数值等效的 Decimal 数字;如果转换失败,则返回零。如果 s 参数为 null 或 String.Empty、格式不符合样式、或者表示的数字小于 MinValue 或大于 MaxValue,则转换将失败。该参数在未初始化的情况下传递;结果中最初提供的任何值都将被覆盖。 - 返回值
类型:System.Boolean
如果 s 转换成功,则为 true;否则为假。
示例
// 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);
关于c# - 使用 C# 验证小费计算器中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52349652/