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

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

    For those that want to right pad, you can do this:

    str2pad := "12"
    padWith := "0"
    amt2pad := 6
    
    //This will make sure there is always 6 characters total, padded on the right side
    //Note to check if strings.Repeat returns a negative value
    paddedStr := str2pad + strings.Repeat(padWith, amt2pad - len(str2pad))
    
    //Outputs 120000
    

提交回复
热议问题