Golang:如何在打印时在数字上加上零? [英] Golang: How to pad a number with zeros when printing?

查看:509
本文介绍了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|\n", 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆