How can I check if a string value is an integer or not in Golang?
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"
As you said, you can use strconv.Atoi for this.
if _, err := strconv.Atoi(v); err == nil {
fmt.Printf("%q looks like a number.
", 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.
import "fmt"
import "regexp"
func main() {
youString :="a12345"
match, _ := regexp.MatchString("([a-z]+)", youString)
if !match{
fmt.Println("Is Number")
} else{
fmt.Println("Not Is Number")
}
}
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.
", v)
}
try it out with v := "12345678900123456789"
You can use unicode.IsDigit()
:
import "unicode"
func isInt(s string) bool {
for _, c := range s {
if !unicode.IsDigit(c) {
return false
}
}
return true
}
You can use govalidator
.
govalidator.IsInt("123") // true
package main
import (
"fmt"
valid "github.com/asaskevich/govalidator"
)
func main() {
fmt.Println("Is it a Integer? ", valid.IsInt("978"))
}
Output:
$ go run intcheck.go
Is it a Integer? true
this might help
func IsInt(s string) bool {
l := len(s)
if strings.HasPrefix(s, "-") {
l = l - 1
s = s[1:]
}
reg := fmt.Sprintf("\\d{%d}", l)
rs, err := regexp.MatchString(reg, s)
if err != nil {
return false
}
return rs
}