c# - 使用 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");
}

好吧,当我尝试 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/

相关文章:

c# - 在 wcf 服务中引用 c++ 库

c# - 比较客户端排序和 SQL Server 排序之间的特性

javascript - 使用 Javascript 在 EditorFor MVC 中获得焦点

c# - 从资源文件设置 image.Source

c# - 在 .NET Core 1.1 csproj 中引用 .NET 4.5 dll?

C# - 具有单个消费者线程的多个生产者线程

c# - 是否可以通过内存映射文件将实例 "pointer"传递给另一个进程?

c# - GMAIL SMTP : A call to SSPI failed exception - The function requested is not supported

c# - 如何通过 api(coding) 在 facebook 中阻止用户

c# - 如何检查 Action 对 View() 的调用没有抛出异常?