This content originally appeared on CodeSource.io and was authored by Deven
In Golang, you can convert string to int type using the following functions.
- strconv.ParseInt(s, base, bitSize)
- strconv.Atoi(s)
Let’s checkout the example of above functions:
1. Golang convert string to int using strconv.ParseInt(s, base, bitSize)
package main
import (
"fmt"
"strconv"
)
func main() {
str := "1111"
n, err := strconv.ParseInt(str, 2, 32)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(n)
}
}
The strconv.ParseInt(s, base, bitSize)
converts the given string to an integer in the given base (0, 2 to 36) and bit size (0 to 64). The output of the above code will be 15
.
2 Golang convert string to int using strconv.Atoi(s) method
package main
import (
"fmt"
"strconv"
)
func main() {
str := "3"
n, _ := strconv.Atoi(str)
fmt.Println(n)
}
we use strconv.Atoi(s)
to convert a string s
to a 32 bit integer. The output of the above code will be 3
.
The post Golang convert string to int – example appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven
Deven | Sciencx (2021-02-07T17:01:26+00:00) Golang convert string to int – example. Retrieved from https://www.scien.cx/2021/02/07/golang-convert-string-to-int-example/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.