Home >Backend Development >Golang >How to Zero-Pad Numbers in Go?

How to Zero-Pad Numbers in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-23 02:20:10292browse

How to Zero-Pad Numbers in Go?

Formatting Numbers with Zero Padding in Go

Printing numbers in a fixed width is a common requirement in programming. In Go, the fmt package provides a convenient way to pad numbers with zeros using the %0 notation.

For example, to pad the number 12 to a width of 6 with zeros, you can use the following code:

fmt.Printf("|%06d|%6d|\n", 12, 345)

Output:

|000012|   345|

The d format specifier tells the fmt package to print the number 12 with a minimum width of 6, padding with zeros as needed. The m format specifier prints 345 with a minimum width of 6, but without any padding.

You can experiment with the fmt package and zero padding here: http://play.golang.org/p/cinDspMccp

The above is the detailed content of How to Zero-Pad Numbers in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn