in C# , how can i check whether the value stored inside a string object( Ex : string strOrderId="435242A") is decimal or not?
9 Answers
Use the Decimal.TryParse function.
decimal value;
if(Decimal.TryParse(strOrderId, out value))
// It's a decimal
else
// No it's not.
3 Comments
Remi Despres-Smyth
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.
Sergey Popov
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.
Pimenta
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 }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);