How to format an integer with zero padding in Julia?

Viewed 228

If I have an Integer, say 123, how can I get a zero-padded string of it to a certain length?

For example, 123 with 6 wide would become "000123", but 1234567 to 6 wide would be "1234567".

3 Answers
julia> string(123, pad=6)
"000123"

Printf is included with Julia and is more flexible, but @MarcMush's answer is cleaner.

julia> using Printf

julia> s = @sprintf("%6.6i",i)
"000123"

There is also Formatting.jl for even more options.

There are lpad and rpad functions.

julia> lpad(123, 6, '0')
"000123"

julia> lpad(1234567, 6, '0')
"1234567"
Related