Ad space (banner)
๐ŸนGo Lessons
Lesson 49 / 68

Formatting Numbers (Padding Digits, Decimal Places)

In this lesson you will learn how to format numbers in Go, lining up digits and decimal places so values display neatly. This is for anyone searching for "Go fmt format verbs how to use".

%.2f fixes the number of decimal places and %03d pads the front of a number with zeros to a fixed width. Both are handy for displaying amounts or generating numbered file names.

The sample code turns 1234.5 into "1234.50 dollars" with two decimal places via fmt.Printf("%.2f dollars\n", price), and turns 7 into the zero-padded "007" via fmt.Printf("%03d\n", num). The fmt package provides a great many format specifiers, known as verbs.

A common stumbling block for beginners is the sheer number of verbs. There are %f for floats, %d for integers, %s for strings and many more, and you have to pick the one that fits. Combining verbs also lets you set width and decimal places at once.

In real-world development number formatting is used constantly on the screens your users see, from aligned money columns to zero-padded order numbers.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)