Home > Backend Development > Golang > How Can I Zero-Pad Numbers in Go's Print Statements?

How Can I Zero-Pad Numbers in Go's Print Statements?

Linda Hamilton
Release: 2025-01-02 12:35:44
Original
213 people have browsed it

How Can I Zero-Pad Numbers in Go's Print Statements?

Zero Padding Numbers in Print Statements

When printing numbers, it is often useful to make them fixed width by adding leading zeros. For instance, if you have the number 12 and want to make it 000012.

The fmt package in Go provides a convenient way to do this. Simply use the format specifier d. The 0 indicates that the number should be padded with zeros, and the 6 specifies the desired width. For example:

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

Output:

|000012|   345|
Copy after login

Note that if the number is too long to fit in the specified width, it will be truncated. For example, if you try to print the number 1234567 with a width of 6, the output will be:

|123456|
Copy after login

In this case, the leading zeros are truncated.

You can also use the fmt package to pad numbers with spaces instead of zeros. To do this, simply use the format specifier m. For example:

fmt.Printf("|%6d|%6d|\n", 12, 345)
Copy after login

Output:

|   12|   345|
Copy after login

The above is the detailed content of How Can I Zero-Pad Numbers in Go's Print Statements?. 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