Home >Backend Development >Golang >How to Zero-Pad Numbers in Go Using fmt.Printf?

How to Zero-Pad Numbers in Go Using fmt.Printf?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-21 13:02:15663browse

How to Zero-Pad Numbers in Go Using fmt.Printf?

Zero-Padding Numeric Strings in Go

When printing integers or creating strings in a fixed width format, it can be useful to zero-pad the value to make it easier to read and compare. This can be achieved using the versatile fmt package in Go.

Problem:

How do you zero-pad a number when printing or converting it to a string to ensure a fixed width?

Solution:

The fmt package provides a convenient formatter for zero-padding numbers:

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

Explanation:

The d format specifier indicates that the number should be printed in a field of width 6 and padded with zeros if necessary. The second argument, m, specifies a field width of 6 but does not include any padding.

Example:

Consider the following example:

package main

import "fmt"

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

Output:

|000012|   345|

As you can see, the number 12 is zero-padded to a width of 6.

Additional Resources:

  • [fmt Package Documentation](https://golang.org/pkg/fmt/)
  • [Zero-Padding Numbers Playground](http://play.golang.org/p/cinDspMccp)

The above is the detailed content of How to Zero-Pad Numbers in Go Using fmt.Printf?. 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