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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1730838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:20:43  来源:igfitidea点击:

C# : Check value stored inside string object is decimal or not

c#decimal

提问by Shyju

in C# , how can i check whether the value stored inside a string object( Ex : string strOrderId="435242A") is decimal or not?

在 C# 中,如何检查存储在字符串对象(例如:string strOrderId="435242A")中的值是否为十进制?

采纳答案by Brandon

Use the Decimal.TryParsefunction.

使用Decimal.TryParse函数。

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

回答by Meta-Knight

You can use Decimal.TryParseto check if the value can be converted to a Decimal type. You could also use Double.TryParseinstead if you assign the result to a variable of type Double.

您可以使用Decimal.TryParse来检查该值是否可以转换为 Decimal 类型。如果将结果分配给 Double 类型的变量,也可以改用Double.TryParse

MSDN example:

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

回答by Jamie M

decimal decValue;

if (decimal.TryParse(strOrderID, out decValue)
{ / *this is a decimal */ }
else
{ /* not a decimal */}

回答by Darin Dimitrov

you may try parsing it:

你可以尝试解析它:

string value = "123";
decimal result;
if (decimal.TryParse(value, out result))
{
    // the value was decimal
    Console.WriteLine(result);
}

回答by anand360

This simple code will allow integer or decimal value and rejects alphabets and symbols.

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

      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
           }

        }

回答by zubair gull

In case if we do not want use extra variable.

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

string strOrderId = "435242A";

bool isDecimal = isDecimal(strOrderId);


public bool isDecimal(string value) {

  try {
    Decimal.Parse(value);
    return true;
  } catch {
    return false;
  }
}

回答by Dale Kilian

Declare decimal out value in TryParse

在 TryParse 中声明十进制输出值

if(Decimal.TryParse(stringValue,out decimal dec))
{
    // ....
}