Go Formatting Verbs

When working with the Printf() function in Go, you’ll have access to a variety of formatting verbs that allow you to control how data is presented.

Tutorials dojo strip



General Formatting Verbs

The following are formatting verbs applicable to all kinds of data types:

VerbDescription
%vDisplays the value in the default format.
%#vOutputs the value in Go-syntax format (ideal for debugging).
%TPresents the type of the value.
%%Prints out a percent sign.

Example Code:

Go

Output:

Go




Integer Formatting Verbs

These formatting verbs work exclusively with integers:

VerbDescription
%bDisplays the binary representation (base 2).
%dShows the decimal representation (base 10).
%+dShows the decimal representation including the sign.
%oDisplays the value in octal format (base 8).
%OOctal format with a leading 0o.
%xOutputs the hexadecimal value (lowercase).
%XOutputs the hexadecimal value (uppercase).
%#xHexadecimal format with a leading 0x.
%4dPads spaces to make it width 4, right-aligned.
%-4dPads spaces to make it width 4, left-aligned.
%04dPads zeroes to make it width 4.

Example Code:

Go

Output:

Go




String Formatting Verbs

For string data types, here are the options:

VerbDescription
%sDisplays the string as it is.
%qWraps the string in double quotes.
%8sAdjusts the width to 8, right-aligned.
%-8sAdjusts the width to 8, left-aligned.
%xConverts the string into hexadecimal format.
% xConverts the string into hexadecimal format with spaces included.

Example Code:

Go

Output:

Go




Boolean Formatting Verbs

Boolean values have a straightforward formatting option:

VerbDescription
%tDisplays the value as true or false.

Example Code:

Go

Output:

Go




Float Formatting Verbs

Here are formatting verbs that deal with floating-point numbers:

VerbDescription
%eShows the number in scientific notation with ‘e’.
%fDisplays the number with a decimal point but without an exponent.
%.2fLimits the precision to 2 decimal points.
%6.2fAdjusts the width to 6 and precision to 2.
%gUses the exponent only if necessary.

Example Code:

Go

Output:

Go

Tutorials dojo strip