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

Viewed 91887

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

9 Answers

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

Take advantage of the discard symbol _ and use

if (decimal.TryParse(stringValue, out _))
{
   // valid decimal 
}
else
{
   // not decimal
}

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
           }

        }

Declare decimal out value in TryParse

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

Think simple.

decimal decNumber = decimal.Parse("9.99");
if (decNumber % 1 > 0)
{
   //decimal area
}
else
{
   //int area
}
Related