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

How to Zero-Pad Numbers in Go?

Susan Sarandon
Release: 2024-12-23 02:20:10
Original
293 people have browsed it

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

Output:

|000012|   345|
Copy after login

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!

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