I needed a function that simply checks if a string can be converted to a valid integer (for form validation).
After searching around, I ended up using a function I had from 2002 which works using C#1 (below).
However, it just seems to me that although the code below works, it is a misuse of try/catch to use it not to catch an error but to determine a value.
Is there a better way to do this in C#3?
public static bool IsAValidInteger(string strWholeNumber)
{
try
{
int wholeNumber = Convert.ToInt32(strWholeNumber);
return true;
}
catch
{
return false;
}
}
John's answer below helped me build the function I was after without the try/catch. In this case, a blank textbox is also considered a valid "whole number" in my form:
public static bool IsAValidWholeNumber(string questionalWholeNumber)
{
int result;
if (questionalWholeNumber.Trim() == "" || int.TryParse(questionalWholeNumber, out result))
{
return true;
}
else
{
return false;
}
}
To check if a string can be converted to an integer:Wrap the call to the int() class in a try/except block. If the conversion succeeds, the try block will fully run. If the conversion to integer fails, handle the ValueError in the except block.
Checking If Given or Input String is Integer or Not Using isnumeric Function. Python's isnumeric() function can be used to test whether a string is an integer or not. The isnumeric() is a builtin function. It returns True if all the characters are numeric, otherwise False.
To check if a String contains digit character which represent an integer, you can use Integer. parseInt() . To check if a double contains a value which can be an integer, you can use Math. floor() or Math.
if (int.TryParse(string, out result))
{
// use result here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With