Is there a better way of testing if a string can be converted to an integer other than something like the following?
Public Function IsInt(ByVal value As Object) As Boolean
Try
Dim temp As Integer = CInt(value)
Return True
Catch ex As Exception
Return False
End Try
End Function
by "better" I mean less verbose and/or w/o an exception.
TryParse would be the way to go, but I'm using the compact framework 2.0 and tryparse doesn't seem to be implemented....
Thanks anyways.
It seems that MarkJ is correct and the above seems to be functionally the same as IsNumeric, so I suppose that's my answer. I don't know why I thought CInt was more strict than IsNumeric. I guess it's better to test using CInt verses IsNumeric since that's the function I'm using to do the conversion?
You can use the following to convert string to int: CInt(String) for ints. CDec(String) for decimals.
You can use the Val function to explicitly convert the digits in a string to a number.
Conversion from string "" to type 'Integer' is not valid. This happens when your database is out of sync with your current MOVEit version. Typically this happens during a migration when the last step 'Perform a repair install' is missed. To fix this you need to repair your database.
You can use the ToString function to convert the calculated field in both your If statement and the return statement, which should resolve your issue.
You can use the built in IsNumeric Function
Dim CanConvert as Boolean = IsNumeric(value)
http://msdn.microsoft.com/en-us/library/6cd3f6w1(VS.71).aspx
Since TryParse isn't supported on the Compact Framework, regex is your next best option.
The first example doesn't allow decimals. The second one does.
Regex.IsMatch(value, "^-?\d+$")
Regex.IsMatch(value, "^-?\d+(?:\.\d+)?$")
If you need to allow for scientific notation, you need to tweak it a little more. It really just isn't that bad. You've got the beginning of the string ^
, an optional dash -?
, one or more digits \d+
, a non-capturing group (?:)
that looks for a single decimal point \.
and one or more digits \d+
. Another ?
to allow either zero or one instances of the non-capturing group, and then the end of the string $
.
Edit:
One thing I didn't think about before: this method is a little imprecise because you could get a really huge number that is numerically a valid integer but can't be converted to an Int32. If that's a possibility, you could constrain the number of characters. Instead of \d+
, you could do \d{1,8}
, for example.
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