HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Check if string is int

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
stringcheckint

Problem

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"

Solution

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.

Code Snippets

if _, err := strconv.Atoi(v); err == nil {
    fmt.Printf("%q looks like a number.\n", v)
}

Context

Stack Overflow Q#22593259, score: 211

Revisions (0)

No revisions yet.