[英]How do I validate a price (number) textbox?
我有一个用C#编写的Windows窗体应用程序。
我正在寻找一种方法来验证我的价格文本框,以便它仅接受双精度格式的价格,例如允许0.01和1200.00,但在用户输入字符时出现错误。
我将除了代码看起来类似于
String price = tbx_price.Text.Trim();
if price is not a number
{
error message
}
else{
...
我可以使用哪种方法检查价格字符串是否仅包含数字? 请注意,我要求用户能够使用小数位,因此“。” 应允许使用字符。
使用decimal.TryParse
:
decimal d;
if (!decimal.TryParse(price, out d)){
//Error
}
并且如果您还想验证价格 ( 145.255
无效):
if (!(decimal.TryParse(price, out d)
&& d >= 0
&& d * 100 == Math.Floor(d*100)){
//Error
}
您可以使用decimal.TryParse()
进行测试。
例如:
decimal priceDecimal;
bool validPrice = decimal.TryParse(price, out priceDecimal);
如果不确定线程的区域性是否与用户的区域性相同,请使用TryParse()
重载,该重载接受区域性格式(也可以将数字格式设置为currency):
public bool ValidateCurrency(string price, string cultureCode)
{
decimal test;
return decimal.TryParse
(price, NumberStyles.Currency, new CultureInfo(cultureCode), out test);
}
if (!ValidateCurrency(price, "en-GB"))
{
//error
}
除了使用标记为已接受的答案以避免与价格有关的文化问题外,您还可以随时使用
Convert.ToDouble(txtPrice.Text.Replace(".", ","));
Convert.ToDouble(txtPrice.Text.Replace(",", "."));
这取决于您如何在应用中管理转化。
PS:我无法评论答案,因为我还没有必要的声誉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.