How to Convert String to Int64 in Golang

To convert string to int64 in Golang, you can “use the strconv.ParseInt() method”. The strconv.ParseInt() function is used to convert a “decimal string (base 10) and checks that it fits into a 64-bit signed integer”.

Example 1: Using ParseInt() function to convert string to int64

package main

import (
  "fmt"
  "strconv"
)

func main() {
  str := "101"
  n, err := strconv.ParseInt(str, 10, 64)
  if err == nil {
    fmt.Printf("%d of type %T", n, n)
  }
}

Output

101 of type int64

Example 2

package main

import (
  "fmt"
  "strconv"
)

func main() {
  v32 := "-354634382"
  if s, err := strconv.ParseInt(v32, 10, 32); err == nil {
    fmt.Printf("%T, %v\n", s, s)
  }
  if s, err := strconv.ParseInt(v32, 16, 32); err == nil {
    fmt.Printf("%T, %v\n", s, s)
  }

 v64 := "-3546343826724305832"
 if s, err := strconv.ParseInt(v64, 10, 64); err == nil {
   fmt.Printf("%T, %v\n", s, s)
 }
 if s, err := strconv.ParseInt(v64, 16, 64); err == nil {
   fmt.Printf("%T, %v\n", s, s)
 }
}

Output

int64, -354634382
int64, -3546343826724305832
That’s all!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.