C#:检查存储在字符串对象中的值是否为十进制

在C#中,我如何检查存储在字符串对象中的值(例如:字符串strOrderId =“435242A”)是否为小数?

使用Decimal.TryParse函数。

decimal value; if(Decimal.TryParse(strOrderId, out value)) // It's a decimal else // No it's not. 

您可以使用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); } 

这个简单的代码将允许整数或十进制值并拒绝字母和符号。

  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; } }