Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string variable has an integer value

Tags:

I am working on a project which allows kids to send a message to Santa. Unfortunately, if they enter a string instead of an integer in the AGE field, the program crashes and returns Conversion from string "[exampleString]" to type 'Double' is not valid. Is there any way to check if they have entered an integer or not? This is the code.

If childAge > 0 And childAge < 150 Then
    fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
    fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If

Thanks, Kai :)

like image 267
Kaimund600 Avatar asked Dec 20 '12 21:12

Kaimund600


People also ask

How do you check if a variable is an integer?

Using int() function The function int(x) converts the argument x to an integer. If x is already an integer or a float with integral value, then the expression int(x) == x will hold true. That's all about determining whether a variable is an integer or not in Python.

How do you check if a string is an integer in Python?

Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .

How do you check if a string is an integer in C?

Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.


2 Answers

A very simple trick is to try parse the string as an Integer. If it succeeds, it is an integer (surprise surprise).

Dim childAgeAsInt As Integer
If Integer.TryParse(childAge, childAgeAsInt) Then
    ' childAge successfully parsed as Integer
Else
    ' childAge is not an Integer
End If
like image 147
Styxxy Avatar answered Nov 02 '22 10:11

Styxxy


Complementing Styxxy's response, if you dont need a result just replace it by vbNull:

If Integer.TryParse(childAge, vbNull) Then
like image 36
Warchlak Avatar answered Nov 02 '22 10:11

Warchlak