[Golang] Type Conversion between String and Integer
Example of Go type conversion (type casting) between string and integer (int64).
Problem
Assume we have the following variable of type string:
intNum := "100"
We will multiply the intNum by 2, convert the result back to string.
Solution
- Convert string to int64:
- Convert int64 to string:
The following code convert string to int64, multiply the number by 2, and then convert the result from int64 back to string.
package main
import (
"fmt"
"strconv"
)
func main() {
intNum := "100"
// convert string to int
n, err := strconv.ParseInt(intNum, 10, 0)
if err != nil {
fmt.Println(err)
return
}
// convert int to string
result := strconv.FormatInt(n*2, 10)
fmt.Println("result: ", result)
}
References:
[1] |
[2] | func ParseInt - strconv - The Go Programming Language |
[3] |
[4] | func FormatInt - strconv - The Go Programming Language |