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

前端 未结 8 1114
广开言路
广开言路 2020-12-09 17:06

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

相关标签:
8条回答
  • 2020-12-09 17:50

    Use the Decimal.TryParse function.

    decimal value;
    if(Decimal.TryParse(strOrderId, out value))
      // It's a decimal
    else
      // No it's not.
    
    0 讨论(0)
  • 2020-12-09 17:54

    you may try parsing it:

    string value = "123";
    decimal result;
    if (decimal.TryParse(value, out result))
    {
        // the value was decimal
        Console.WriteLine(result);
    }
    
    0 讨论(0)
  • 2020-12-09 18:04

    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;
      }
    }
    
    0 讨论(0)
  • 2020-12-09 18:04

    Declare decimal out value in TryParse

    if(Decimal.TryParse(stringValue,out decimal dec))
    {
        // ....
    }
    
    0 讨论(0)
  • 2020-12-09 18:05
    decimal decValue;
    
    if (decimal.TryParse(strOrderID, out decValue)
    { / *this is a decimal */ }
    else
    { /* not a decimal */}
    
    0 讨论(0)
  • 2020-12-09 18:06

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

    MSDN example:

    string value = "1,643.57";
    decimal number;
    if (Decimal.TryParse(value, out number))
       Console.WriteLine(number);
    else
       Console.WriteLine("Unable to parse '{0}'.", value);
    
    0 讨论(0)
提交回复
热议问题