Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number to string with leading (left padded) zeros in Julialang

It seems as an easy question, but I cannot find the answer anywhere. If I have an integer variable, how can I transform it to a string with leading zeros?

I want something as the code below:

n = 4
string_size = 3
println(fleading(n, string_size)) 
# result should be "004"

Where fleading would be something like the function to transform the number to string with leading zeros. The analogous way in python is str(4).zfill(3) which gives 004 as result.

like image 233
silgon Avatar asked Aug 24 '16 19:08

silgon


2 Answers

You're looking for the lpad() (for left pad) function:

julia> lpad(4,3,"0")
"004"

Note the last argument must be a string.

From the documentation:

lpad(string, n, "p")

Make a string at least n columns wide when printed, by padding on the left with copies of p.

like image 54
Michael Ohlrogge Avatar answered Sep 20 '22 14:09

Michael Ohlrogge


For Julia 1.0 the syntax is:

lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ')

The example is therefore:

julia> lpad(4, 3, '0')
004
like image 29
Martin Avatar answered Sep 20 '22 14:09

Martin