W3Basic Logo

Convert string to integer type in Go

In this article, we will discuss different approaches to converting a string to integer type in Golang with examples.


Using the strconv package:

The strconv.Atoi function converts a string to an integer. It returns two values: the converted integer and an error. In this example, we use the blank identifier _ to ignore the error value.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    s := "101"
    i, _ := strconv.Atoi(s)
    fmt.Println(i) // Output: 101`
}

Output

101

Using the ParseInt function from the strconv package:

The strconv.ParseInt function takes three arguments:

  • The string to convert.
  • The base of the number is represented by the string (10 for decimal).
  • The bit size (either 32 or 64).

It returns the converted integer and an error.In this example, we use the blank identifier _ to ignore the error value.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    s := "33"
    i, _ := strconv.ParseInt(s, 10, 64)
    fmt.Println(i) // Output: 33
}

Output

33

Using the ParseFloat function from the strconv package:

The strconv.ParseFloat function takes two arguments: the string to convert and the bit size (either 32 or 64). It returns the converted float and an error.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    s := "42.0"
    f, _ := strconv.ParseFloat(s, 64)
    i := int(f)
    fmt.Println(i) // Output: 42
}

Output

42

Note: The above examples ignore the error returned by the function; it's better to check the error before using the value returned, as some of the input string might not be able to convert to an integer.

Conclusion:

In conclusion, converting a string to an integer in Golang is a straightforward process, and with the help of built-in functions like strconv.Atoi, strconv.ParseInt, and strconv.ParseFloat, you can easily convert a string to int. Finally, remember to check the error returned by the function before using the value returned, as some input strings might not be able to convert to an integer.

© 2023 W3Basic. All rights reserved.

Follow Us: