【发布时间】:2009-11-13 17:45:16
【问题描述】:
在 C# 中,我如何检查存储在字符串对象中的值(例如:字符串 strOrderId="435242A")是否为十进制?
【问题讨论】:
在 C# 中,我如何检查存储在字符串对象中的值(例如:字符串 strOrderId="435242A")是否为十进制?
【问题讨论】:
使用Decimal.TryParse 函数。
decimal value;
if(Decimal.TryParse(strOrderId, out value))
// It's a decimal
else
// No it's not.
【讨论】:
if (!Decimal.TryParse(strOrderId, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out decimalNumber) || strOrderId.IndexOf(",") > -1) { // not Decimal } else { // decimal }
您可以使用Decimal.TryParse 来检查该值是否可以转换为Decimal 类型。如果将结果分配给 Double 类型的变量,也可以使用 Double.TryParse。
MSDN 示例:
string value = "1,643.57";
decimal number;
if (Decimal.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
【讨论】:
decimal decValue;
if (decimal.TryParse(strOrderID, out decValue)
{ / *this is a decimal */ }
else
{ /* not a decimal */}
【讨论】:
你可以尝试解析它:
string value = "123";
decimal result;
if (decimal.TryParse(value, out result))
{
// the value was decimal
Console.WriteLine(result);
}
【讨论】:
如果我们不想使用额外的变量。
string strOrderId = "435242A";
bool isDecimal = isDecimal(strOrderId);
public bool isDecimal(string value) {
try {
Decimal.Parse(value);
return true;
} catch {
return false;
}
}
【讨论】:
利用丢弃符号_并使用
if (decimal.TryParse(stringValue, out _))
{
// valid decimal
}
else
{
// not decimal
}
【讨论】:
这个简单的代码将允许整数或十进制值,并拒绝字母和符号。
foreach (char ch in strOrderId)
{
if (!char.IsDigit(ch) && ch != '.')
{
MessageBox.Show("This is not a decimal \n");
return;
}
else
{
//this is a decimal value
}
}
【讨论】:
在 TryParse 中声明小数输出值
if(Decimal.TryParse(stringValue,out decimal dec))
{
// ....
}
【讨论】:
想得简单。
decimal decNumber = decimal.Parse("9.99");
if (decNumber % 1 > 0)
{
//decimal area
}
else
{
//int area
}
【讨论】: