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

前端 未结 6 1169
再見小時候
再見小時候 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:12

    There is one simplest way to achieve this. Use

    func padNumberWithZero(value uint32) string {
        return fmt.Sprintf("%02d", value)
    }
    

    fmt.Sprintf formats and returns a string without printing it anywhere. Here %02d says pad zero on left for value who has < 2 number of digits. If given value has 2 or more digits it will not pad. For example:

    • If input is 1, output will be 01.
    • If input is 12, output will be 12.
    • If input is 1992, output will be 1992.

    You can use %03d or more for more zeros padding.

提交回复
热议问题