19

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

0

9 Answers 9

37

Use the Decimal.TryParse function.

decimal value;
if(Decimal.TryParse(strOrderId, out value))
  // It's a decimal
else
  // No it's not.
3
  • 3
    This will only work if any number can be considered a Decimal. If you need to distinguish between numeric types, it'll consider integral types as decimals as well. Apr 17, 2012 at 12:56
  • You should consider decimal format and current culture. For example, correct decimal value for en-Us 643.57 doesn't parsing in ru-RU culture by this method. Mar 5, 2014 at 15:41
  • 1
    I know this is old, but I add some extra validations and also check for a decimal comma, witch in my case is the decimal separator. if (!Decimal.TryParse(strOrderId, System.Globalization.NumberStyles.Any, CultureInfo.InvariantCulture, out decimalNumber) || strOrderId.IndexOf(",") > -1) { // not Decimal } else { // decimal }
    – Pimenta
    Aug 23, 2017 at 10:44
30

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);
5
decimal decValue;

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

Take advantage of the discard symbol _ and use

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

you may try parsing it:

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

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

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
           }

        }
1

Think simple.

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

Declare decimal out value in TryParse

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.