Golang: How to pad a number with zeros when printing?

前端 未结 6 1174
再見小時候
再見小時候 2020-12-12 19:01

How can I print a number or make a string with zero padding to make it fixed width?

For instance, if I have the number 12 and I want to make it 00

6条回答
  •  孤城傲影
    2020-12-12 19:09

    The fmt package can do this for you:

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

    Output:

    |000012|   345|
    

    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.

    Try it for yourself here: http://play.golang.org/p/cinDspMccp

提交回复
热议问题