Is there a better way to validate an integer in C # than Double.TryParse?
I would definitely think what you need to define. "Is a number" is more uncertain than meets the eye. Consider the following lines and whether you want to count them as numeric:
- "NaN"
- "Nan"
- "infinity"
- "0.000000000000000000000000000000000000000000000000001"
- "1e5"
- "1e500"
- "1000"
- "+ 1"
Using Double.TryParse
(with en-GB culture - don't forget cultural issues!) Will give you True, False, True, True (although not imaginable), True, False. True true.
If you want to know if a later call will Double.TryParse
succeed, calling it here would be the most accurate solution. If you are using some other criteria, a regex may be more appropriate. An example of criteria you can use:
- May be + or -, but only in the first character
- There can be one period for any symbol. You might want to avoid the one at the end - followed by "1." acceptable?
- Apart from the above, all characters must be numbers
This will be prohibited to everyone except the fourth and final example above.
EDIT: Now I noticed that the title of the question includes "integer". This greatly reduces the checking of specifications for:
- Do you want to allow leading zeros (e.g. -00012)?
- What is the range?
- Do you only want decimal places (instead of hex, etc.)?
- Do you need to accept thousands separators?
- What is your policy for leading / trailing spaces?
source to share
I just released Visual Studio Express (2005 and 2008). Intellisense says the return value of Double.TryParse () is a bool. The following worked for me on limited testing ...
double res; // you must be under very resource-constrained
// conditions if you can't just declare a double
// and forget about it
if (Double.TryParse(textBox1.Text, out res)) {
label1.Text = "it a number";
} else {
label1.Text = "not a number";
}
source to share