C# : Check value stored inside string object is decimal or not
in C# , how can i check whether the value stored inside a string object( Ex : s开发者_开发技巧tring strOrderId="435242A") is decimal or not?
Use the Decimal.TryParse function.
decimal value;
if(Decimal.TryParse(strOrderId, out value))
// It's a decimal
else
// No it's not.
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);
decimal decValue;
if (decimal.TryParse(strOrderID, out decValue)
{ / *this is a decimal */ }
else
{ /* not a decimal */}
you may try parsing it:
string value = "123";
decimal result;
if (decimal.TryParse(value, out result))
{
// the value was decimal
Console.WriteLine(result);
}
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
}
}
Think simple.
decimal decNumber = decimal.Parse("9.99");
if (decNumber % 1 > 0)
{
//decimal area
}
else
{
//int area
}
Declare decimal out value in TryParse
if(Decimal.TryParse(stringValue,out decimal dec))
{
// ....
}
精彩评论