C#:检查字符串对象中存储的值是否为十进制
在C#中,如何检查存储在字符串对象(例如:string strOrderId=“435242A”)中的值是否为十进制 您可以使用来检查该值是否可以转换为十进制类型。如果将结果赋给Double类型的变量,也可以使用 MSDN示例:C#:检查字符串对象中存储的值是否为十进制,c#,decimal,C#,Decimal,在C#中,如何检查存储在字符串对象(例如:string strOrderId=“435242A”)中的值是否为十进制 您可以使用来检查该值是否可以转换为十进制类型。如果将结果赋给Double类型的变量,也可以使用 MSDN示例: string value = "1,643.57"; decimal number; if (Decimal.TryParse(value, out number)) Console.WriteLine(number); else Console.Write
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 value;
if(Decimal.TryParse(strOrderId, out value))
// It's a decimal
else
// No it's not.
您可以尝试解析它:
string value = "123";
decimal result;
if (decimal.TryParse(value, out result))
{
// the value was decimal
Console.WriteLine(result);
}
这个简单的代码将允许整数或十进制值,并拒绝字母和符号
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
}
}
如果我们不想使用额外的变量
string strOrderId = "435242A";
bool isDecimal = isDecimal(strOrderId);
public bool isDecimal(string value) {
try {
Decimal.Parse(value);
return true;
} catch {
return false;
}
}
在TryParse中声明十进制输出值
if(Decimal.TryParse(stringValue,out decimal dec))
{
// ....
}
简单想想
decimal decNumber = decimal.Parse("9.99");
if (decNumber % 1 > 0)
{
//decimal area
}
else
{
//int area
}
只有当任何数字都可以被视为十进制时,这才有效。如果需要区分数字类型,它也将将整数类型作为小数,应考虑十进制格式和当前区域性。例如,en Us 643.57的正确十进制值不能通过此方法在ru区域性中进行解析。我知道这是旧的,但我添加了一些额外的验证,还检查了十进制逗号,在我的示例中是十进制分隔符<代码>如果(!Decimal.TryParse(strOrderId,System.Globalization.NumberStyles.Any,CultureInfo.InvariantCulture,out decimalNumber)| | strOrderId.IndexOf(“,”>)-1){//not Decimal}否则{//Decimal
decimal decNumber = decimal.Parse("9.99");
if (decNumber % 1 > 0)
{
//decimal area
}
else
{
//int area
}