Search code examples
stringgouint32leading-zero

Convert uint32 to string and add leading 0s


I need to convert uint32 to a string and add leading zeroes to a fixed length. How can I do that?

Here's my code:

var unixTs uint32 = 1446455472
var randomInt uint32 = 58964981
var expiredTs uint32 = 2

unixTsStr := fmt.Sprint("%010d", unixTs)
randomIntStr := fmt.Sprint("%08d", randomInt)
expiredTsStr := fmt.Sprint("%010d", expiredTs)

Output prints:

%010d1446455472
%08d58964981
%010d2

What I want is:

1446455472
58964981
0000000002

Thanks!


Solution

  • Use fmt.Sprintf instead of fmt.Sprint. Sprintf formats according to a format specifier. Sprint formats using the default format for each argument.

    playground example