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
Release: 2024-12-21 13:02:15
Original
622 people have browsed it

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)
Copy after login

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)
}
Copy after login

Output:

|000012|   345|
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template