How to use the strconv.FormatInt() function in Go
The go strconv.FormatInt() function
The strconv package’s FormatInt() function is used to obtain the string representation of a given integer in a chosen base, which can range from 2 to 36 (2 <= base <= 36). For digit values greater >= 10, the output uses lower-case letters a to z.
Syntax
func FormatInt(i int64, base int) string
Parameters
i: The integer value to be converted in the string format.base: The given base value.
Return value
The function FormatInt() returns the string representation of the given integer in the given base.
Example
The following code shows how to implement the strconv.FormatInt() function in Go.
// Using strconv.FormatFloat() Functionpackage mainimport ("fmt""strconv")func main() {// declaring variablevar num int64// Assign valuenum = 2634// returns a string typefmt.Println(strconv.FormatInt(num, 10))fmt.Println()// reassign valuenum = 186// returns a string typefmt.Println(strconv.FormatInt(num, 2))fmt.Println()// reassign valuenum = 86// returns a string typefmt.Println(strconv.FormatInt(num, 16))fmt.Println()}
Code explanation
- Line 4: We add the
mainpackage. - Lines 6–9: We import the necessary packages.
- Lines 11–31: We define the
main()function, variable num ofint64type, and assign a value to it. Next, we pass the variable to theFormatInt()function, which converts the integer value to a string given thebaseparameter.