How to convert string to integer type in Go ?

How to convert string to integer type in Go ?

Asked on December 18, 2018 in String.
Add Comment


  • 2 Answer(s)

    Try this code:

    For example,

    package main
    import (
        "flag"
        "fmt"
        "os"
        "strconv"
    )
     
    func main() {
        flag.Parse()
        s := flag.Arg(0)
        // string to int
        i, err := strconv.Atoi(s)
        if err != nil {
        // handle error
        fmt.Println(err)
        os.Exit(2)
        }
        fmt.Println(s, i)
    }
    
    Answered on December 18, 2018.
    Add Comment

    Try this solution:

    There are three ways to parse strings into integers, from fastest runtime to slowest:

      • strconv.ParseInt() fastest
      • strconv.Atoi() still very fast
      • fmt.Sscanf() not terribly fast but most flexible

    A benchmark that shows usage and example timing for each function:

    package main
     
    import "fmt"
    import "strconv"
    import "testing"
     
    var num = 123456
    var numstr = "123456"
     
    func BenchmarkStrconvParseInt(b *testing.B) {
        num64 := int64(num)
        for i := 0; i < b.N; i++ {
            x, err := strconv.ParseInt(numstr, 10, 64)
            if x != num64 || err != nil {
                b.Error(err)
            }
        }
    }
    func BenchmarkAtoi(b *testing.B) {
        for i := 0; i < b.N; i++ {
            x, err := strconv.Atoi(numstr)
            if x != num || err != nil {
                b.Error(err)
            }
        }
    }
    func BenchmarkFmtSscan(b *testing.B) {
        for i := 0; i < b.N; i++ {
            var x int
            n, err := fmt.Sscanf(numstr, "%d", &x)
            if n != 1 || x != num || err != nil {
                b.Error(err)
            }
        }
    }
    

    Run it by saving as atoi_test.go and running go test -bench=. atoi_test.go.

    goos: darwin
    goarch: amd64
    BenchmarkStrconvParseInt-8 100000000 17.1 ns/op
    BenchmarkAtoi-8 100000000 19.4 ns/op
    BenchmarkFmtSscan-8 2000000 693 ns/op
    PASS
    ok command-line-arguments 5.797s
    
    Answered on December 18, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.