Home >Backend Development >Golang >How Can I Pad Numbers with Leading Zeros in Go?

How Can I Pad Numbers with Leading Zeros in Go?

DDD
DDDOriginal
2024-12-23 22:55:14339browse

How Can I Pad Numbers with Leading Zeros in Go?

Padding Numbers with Zeros for Printing

In Go, you can easily pad numbers with zeros when printing them to make them fixed width. This can be useful for alignment or other formatting purposes.

Using the fmt Package

The fmt package provides a way to format numbers and strings with various options, including padding. To pad a number with zeros, you can use the %0d format specifier. The placeholder specifies the desired width of the padded string, and the 0 indicates that it should be padded with zeros.

For example:

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

This will output:

|000012|   345|

Notice the 0 in d, which indicates that the number should be padded with zeros to a width of 6. The second m will pad the number with spaces.

Play it Yourself

Try out the code for yourself at the following URL:

http://play.golang.org/p/cinDspMccp

The above is the detailed content of How Can I Pad Numbers with Leading Zeros 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