Golang String To Int Conversion Example

Go (Golang) offers a vast standard library with a lot tools coming directly out of the box for most every day tasks. One of this is the conversion of strings to numeric values. For this kind of problem we have an handful of different options, here some of them:

Use strconv.ParseInt

One option is strconv.ParseInt. Which gives you a lot of flexibility on what numeric base (base 2, 10, 16 etc) the expected integer is supposed to be and the bitsize (16, 32, 64 etc) of the integer you are trying to parse.

func ParseInt(s string, base int, bitSize int) (int64, error)  

ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.
If the base argument is 0, the true base is implied by the string’s prefix: 2 for “0b”, 8 for “0” or “0o”, 16 for “0x”, and 10 otherwise. Also, for argument base 0 only, underscore characters are permitted as defined by the Go syntax for integer literals.
The bitSize argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64. If bitSize is below 0 or above 64, an error is returned.
The errors that ParseInt returns have concrete type *NumError and include err.Num = s. If s is empty or contains invalid digits, err.Err = ErrSyntax and the returned value is 0; if the value corresponding to s cannot be represented by a signed integer of the given size, err.Err = ErrRange and the returned value is the maximum magnitude integer of the appropriate bitSize and sign.

Here’s an example below

package main
        
import (
    "strconv"
    "log"
)
        
func main() {
    i, err := strconv.ParseInt("12345", 10, 64)
    if err != nil {
        log.Fatal(err)
    }
    log.Println(i)
} 

This is the expected output

2009/11/10 23:00:00 12345    

Use strconv.Atoi

One options is to use strconv.Atoi function which is much quicker to use as it’s using by default a decimal base.

func Atoi(s string) (int, error) 

Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

Here’s an example below

package main

import (
    "strconv"
    "log"
)
        
func main() {
   i, err := strconv.Atoi("12345")
   if err != nil {
        log.Fatal(err)
    }
    log.Println(i)
} 

This is the expected output for the much simpler strconv.Atoi function

2009/11/10 23:00:00 12345    

Use fmt.Sscanf

One more sophisticated option is to use the fmt.Sscanf function. Which allows you to parse integer values inside strings but using different format options

func Sscanf(str string, format string, a ...interface{}) (n int, err error)    

Sscanf scans the argument string, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.

Let’s see an example to better understand its possible use cases

package main

import (
    "fmt"
)

func main() {
    var userID, sessionID int
    _, err := fmt.Sscanf("UserID:12345 SessionID:54321", "UserID:%d SessionID:%d", &userID, &sessionID)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%d, %d\n", userID, sessionID)
}   

Here’s an example of the output for this code snippet

12345, 54321
Join the Golang Developers Community on Golang Cafe