Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang converting string to int64

Tags:

string

go

int64

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?

like image 522
Qian Chen Avatar asked Feb 03 '14 16:02

Qian Chen


People also ask

How do I convert to Int64?

To convert a Double value to an Int64 value, use the Convert. ToInt64() method. Int64 represents a 64-bit signed integer.


2 Answers

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

like image 101
ET-CS Avatar answered Oct 20 '22 11:10

ET-CS


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.

Adding abbreviated example:

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

like image 42
Eve Freeman Avatar answered Oct 20 '22 10:10

Eve Freeman