Csharp/C#教程:C#:检查存储在字符串对象中的值是否为十进制分享


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

如果我们不想使用额外的变量。

上述就是C#学习教程:C#:检查存储在字符串对象中的值是否为十进制分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 string strOrderId = "435242A"; bool isDecimal = isDecimal(strOrderId); public bool isDecimal(string value) { try { Decimal.Parse(value); return true; } catch { return false; } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/951045.html

(0)
上一篇 2021年11月18日
下一篇 2021年11月18日

精彩推荐