133

I want to convert a string to an int64. What I find from the strconv package is the Atoi function. It seems to cast a string to an int and return it:

// Atoi is shorthand for ParseInt(s, 10, 0).
func Atoi(s string) (i int, err error) {
        i64, err := ParseInt(s, 10, 0)
    return int(i64), err
}

The ParseInt actually returns an int64:

func ParseInt(s string, base int, bitSize int) (i int64, err error){
     //...
}

So if I want to get an int64 from a string, should I avoid using Atoi, instead use ParseInt? Or is there an Atio64 hidden somewhere?

  • `int` is a signed integer type that is *at least 32 bits* in size. It is a distinct type, however, and not an alias for `int32`. So you're good to use it and won't incur data loss in int64 range too – Ayush Kumar Feb 21 '22 at 06:42

3 Answers3

243

Parsing string into int64 example:

// Use the max value for signed 64 integer. http://golang.org/pkg/builtin/#int64
var s string = "9223372036854775807"
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
    panic(err)
}
fmt.Printf("Hello, %v with type %s!\n", i, reflect.TypeOf(i))

output:

Hello, 9223372036854775807 with type int64!

https://play.golang.org/p/XOKkE6WWer

ET-CS
  • 6,334
  • 5
  • 43
  • 73
  • 2
    I think this should be marked as the correct answer. – Lucat Aug 15 '18 at 12:53
  • 4
    One could also remove usage of reflect and use it just like; `fmt.Printf("Hello, %v with type %T!\n", i, i)` or even taking it another step further, one could use; `fmt.Printf("Hello, %v with type %[1]T!\n", i)` – Ilgıt Yıldırım Oct 04 '19 at 06:01
  • I recommend strings.TrimSpace() because some unintended whitespace could change the numeric value by accident. – PJ Brunet May 10 '22 at 08:30
107

No, there's no Atoi64. You should also pass in the 64 as the last parameter to ParseInt, or it might not produce the expected value on a 32-bit system.

var s string = "9223372036854775807"
i, _ := strconv.ParseInt(s, 10, 64)
fmt.Printf("val: %v ; type: %[1]T\n", i)

https://play.golang.org/p/FUC8QO0-lYn

Westy92
  • 19,087
  • 4
  • 72
  • 54
Eve Freeman
  • 32,467
  • 4
  • 86
  • 101
5

Another option:

package main
import "fmt"

func main() {
   var n int64
   fmt.Sscan("100", &n)
   fmt.Println(n == 100)
}

https://golang.org/pkg/fmt#Sscan

Zombo
  • 1
  • 62
  • 391
  • 407