HelloKoding

Practical coding guides

Convert string to int in Golang

In Golang, to convert string to int you can use strconv.Atoi(s) and strconv.ParseInt(s, base, bitSize). Lets walk through this tutorial to see the examples in practice

Convert string to int with strconv.Atoi(s)

  • You can use strconv.Atoi(s) to convert a string s to a 32 bit integer. Atoi stands for ASCII to integer
package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "1"

	n, _ := strconv.Atoi(str)
	fmt.Println(n)
}

Output

1
  • If the input string isn’t in the integer format, you would get the zero value in return
package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "1.9"

	n, _ := strconv.Atoi(str)
	fmt.Println(n)
}

Output

0
  • Beside returns integer value, strconv.Atoi(s) also returns an error in case the converting isn’t successful
package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "1a"

	n, err := strconv.Atoi(str)

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(n)
	}
}

Output

strconv.Atoi: parsing "1a": invalid syntax

Convert string to int with strconv.ParseInt(s, base, bitSize)

The strconv.ParseInt(s, base, bitSize) convert the given string s to an integer in the given base (0,2 to 36) and bit size (0 to 64)

Atoi(s) is equivalent to Parseint(s, 10, 0)

parseint.go

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "1001"

	n, err := strconv.ParseInt(str, 2, 32)

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(n)
	}
}

Output

9
Follow HelloKoding