Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
strconv
communitycreator
communitymanager

How to use strconv.FormatUint() Function in Golang

Maria Elijah

Golang strconv.FormatUnit() function

The FormatUint() function is a strconv package built-in function that returns the string representation of an unsigned integer i in a given base, where the base can range from 2 to 36. For digit values greater than 10, the lower-case letters ‘a’ to ‘z’ are returned.

Syntax

func FormatUint(i uint64, base int) string

Parameters

  • i: An unsigned integer value that will be converted to a string
  • base: is the base of the given value.

Return value

The strconv.FormatUint() function returns the string representation of i in a given base(2 <= base <= 36).

Code

The following code shows how to implement the strconv.FormatUint() function in Golang.

// Golang program to illustrate
// strconv.FormatUint() Function
package main

import (
	"fmt"
	"strconv"
)

func main() {
  // declaring variable y as unsigned integer
  var y uint64
  // declaring variable res as string type
  var res string
	// assigning value
	y = 28
	//  Finds the string representation
    // of y value in the base 2
	// stores the result in variable res
	res = strconv.FormatUint(y, 2)
	// display result
	fmt.Printf("\nVariable y is a Type %T", res)
	fmt.Printf("\nResult is %v\n", res)

	// reassigning value 
	y = 102
	//  Finds the string representation
    // of y value in the base 16
	// stores the result in variable res
	res = strconv.FormatUint(y, 16)
	// display result
	fmt.Printf("\nReassign value of y\n")
	fmt.Printf("\nVariable y is a Type %T", res)
	fmt.Printf("\nResult is %v", res)

}

Code explanation

  • Line 4: Adding package main.

  • Lines 5 to 8: Importing necessary packages in Golang project.

  • Lines 11 - 21: Defining the main() function, variable y of unsigned integer and assign a value to it, then passed the variable in the strconv.FormatUint() function which finds the string representation of y value in the base 2. The result is stored in variable res, which is finally displayed.

RELATED TAGS

golang
strconv
communitycreator
communitymanager
RELATED COURSES

View all Courses

Keep Exploring