数字(本例中为decimal)与其字符串表示(本例中为货币)不同。这就是为什么您必须首先从字符串的角度分析输入(格式是否满足?),然后从数字的角度分析。有一些方法可以一次性执行分析(如其他答案中所建议的那样),尽管它们不能提供您所追求的确定(即,它是否是一种货币;理解为仅仅是数字是错误的)。
示例代码:
private void btn_Click(object sender, EventArgs e)
{
//Note: ideally, curCulture shouldn't be defined here (but globally or
//passed as argument), but otherwise my code would be somehow incomplete.
CultureInfo curCulture = new CultureInfo("en-US", true);
bool isOK = false;
string[] temp = totalTextBox.Text.Trim().Split(new string[] { curCulture.NumberFormat.CurrencySymbol }, StringSplitOptions.None);
if (temp.Length == 2 && temp[0].Trim().Length == 0)
{
decimal outVal = 0m;
if (decimal.TryParse(temp[1], out outVal)) isOK = true;
}
MessageBox.Show(isOK ? "currency format" : "error wrong format");
}
注意几点:
-
curCulture 应该是你想要的格式(你甚至可以
考虑不同的文化/货币/格式)。从你的例子看来,你
想要:CultureInfo curCulture = new CultureInfo("en-US", true);。
- 输入字符串的分析可以根据需要复杂。例如:在发布的代码中,我还确保货币符号位于第一个位置。
---- UPDATE(考虑千位分隔符的十进制解析问题)
在确认提议的Decimal.TryParse(和其他等效方法)在涉及数千个分隔符(组分隔符)时不能提供预期的结果后,我决定编写下面的代码来处理此类问题.
在任何情况下,请记住,我在这些情况下没有太多经验(即处理错误的十进制输入占数千个分隔符),这就是为什么不确定是否有更有效的方法来解决这个问题(尽管建议的分析肯定很快)。
private void btn_Click(object sender, EventArgs e)
{
//Note: ideally, curCulture shouldn't be defined here (but globally or
//passed as argument), but otherwise my code would be somehow incomplete.
CultureInfo curCulture = new CultureInfo("en-US", true);
bool isOK = false;
string[] temp = totalTextBox.Text.Trim().Split(new string[] { curCulture.NumberFormat.CurrencySymbol }, StringSplitOptions.None);
if (temp.Length == 2 && temp[0].Trim().Length == 0)
{
isOK = isDecimalOK(temp[1], curCulture);
}
MessageBox.Show(isOK ? "currency format" : "error wrong format");
}
private bool isDecimalOK(string inputString, CultureInfo curCulture)
{
bool isOK = false;
string[] temp = inputString.Split(new string[] { curCulture.NumberFormat.CurrencyDecimalSeparator }, StringSplitOptions.None);
if (temp.Length > 2) return isOK;
int outVal0 = 0;
if (!int.TryParse(temp[0], NumberStyles.AllowThousands, curCulture, out outVal0)) return isOK;
else if (analyseThousands(temp[0], curCulture))
{
isOK = (temp.Length == 2 ? int.TryParse(temp[1], NumberStyles.Integer, curCulture, out outVal0) : true);
}
return isOK;
}
private bool analyseThousands(string intInput, CultureInfo curCulture)
{
string[] temp2 = intInput.Split(new string[] { curCulture.NumberFormat.CurrencyGroupSeparator }, StringSplitOptions.None);
if (temp2.Length >= 2)
{
if (temp2[0].Trim().Length == 0) return false;
else
{
for (int i2 = 1; i2 < temp2.Length; i2++)
{
if (!curCulture.NumberFormat.CurrencyGroupSizes.Contains(temp2[i2].Length)) return false;
}
}
}
return true;
}