How can I check if a string value is an integer or not in Go?
Something like
v := "4"
if isInt(v) {
fmt.Println("We have an int, we can safely cast this with strconv")
}
Note: I know that strconv.Atoi
returns an error, but is there any other function to do this?
The problem with strconv.Atoi
is that it will return 7
for "a7"
Data types in Python One example of a data type is strings. Strings are sequences of characters that are used for conveying textual information. Ints, or integers, are whole numbers.
To check if a string is integer in Python, use the isdigit() method. The string isdigit() is a built-in Python method that checks whether the given string consists of only digits. In addition, it checks if the characters present in the string are digits or not.
To check if a string is an integer or a float:Use the str. isdigit() method to check if every character in the string is a digit. If the method returns True , the string is an integer. If the method returns False , the string is a floating-point number.
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.
How can I check if a string value is an integer or not in Go? Something like v := "4" if isInt(v) { fmt.Println("We have an int, we can safely cast this with strconv") } Note... Stack Overflow About Products For Teams Stack OverflowPublic questions & answers
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.
How to check if a C/C++ string is an int? There are several methods to check that string is an int or not and one of those method is to use isdigit () to check the string. Here is an example to check whether a string is an int or not in C++ language,
You can use Integer.parseInt () or Integer.valueOf () to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch the NumberFormatException it can throw. It may be helpful to note that valueOf () will return an Integer object, not the primitive int.
As you said, you can use strconv.Atoi for this.
if _, err := strconv.Atoi(v); err == nil {
fmt.Printf("%q looks like a number.\n", v)
}
You could use scanner.Scanner
(from text/scanner
) in mode ScanInts
, or use a regexp to validate the string, but Atoi
is the right tool for the job.
this is better, you can check for ints upto 64 ( or less ) bits
strconv.Atoi only supports 32 bits
if _, err := strconv.ParseInt(v,10,64); err == nil {
fmt.Printf("%q looks like a number.\n", v)
}
try it out with v := "12345678900123456789"
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