Golang:打印时如何用零填充数字? [英] Golang: How to pad a number with zeros when printing?
本文介绍了Golang:打印时如何用零填充数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何打印一个数字或用零填充制作一个字符串以使其固定宽度?
How can I print a number or make a string with zero padding to make it fixed width?
例如,如果我有数字 12
并且我想使它成为 000012
.
For instance, if I have the number 12
and I want to make it 000012
.
推荐答案
fmt 包可以为您做到这一点:
The fmt package can do this for you:
fmt.Printf("|%06d|%6d|
", 12, 345)
输出:
|000012| 345|
注意 %06d 中的 0,这将使它的宽度为 6 并用零填充它.第二个将填充空格.
Notice the 0 in %06d, that will make it a width of 6 and pad it with zeros. The second one will pad with spaces.
在这里自己试试:http://play.golang.org/p/cinDspMccp
这篇关于Golang:打印时如何用零填充数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文