Leading Zeros

Hi,

I have a simple question but i cannot find the answer. I have an array of integers between 1 to 999. I need the left pading of 3 so that every element is composed of 3 digits.E.g. [ 001, 002,…090…, 900]. But I would strongly prefer them to be Integers, LPAD() outputs strings.

Is that possible?

Looks like you can use the lpad function

lpad(string(n), 3, '0')

You can quickly run this on an entire array with broadcasting

lpad.(string.(v), 3, '0')

Where do you want this to happen? When the array is printed?

I don’t think that’s possible since 3 == 003. If you have the bitstring for an integer 00000011 is that 3 or 03 or 003…?

Of course, there are ways around that, using a string, making a custom type with the number of leading zeros in it, storing the digits in an array (the digits-function) etc. But none of these are integers.

Maybe we can help you find a good solution if you tell us a little more about why you want it exactly this way; probably there is a good alternative.

Sorry, now I think I was confused by the question. I would agree with @giordano the only solution is to do this wherever the output is happening. You don’t want to just make all integers display that way by default, trust me.

Hi,

Thanks for the fast reply! if I left pad it to “002”. How can I explode it so it is [‘0’,‘0’,‘2’]?

best,

julia> digits(2, pad = 3)
3-element Array{Int64,1}:
 2
 0
 0

collect("002")

Although, if you have a number and want digits as numbers, there’s no need to go through strings.

wasn’t aware of digits() could work this way as well :slight_smile: thanks!

using Printf
for i in 1:999
    @printf("%03d\n", i)
end
001
002
003 ...

Can also render padded binary output:

    @printf("%6i → %s → %03d\n", i, string(i, base=2, pad=11), i)
end
     1 → 00000000001 → 001
     2 → 00000000010 → 002
     3 → 00000000011 → 003
     4 → 00000000100 → 004
     5 → 00000000101 → 005
     6 → 00000000110 → 006
     7 → 00000000111 → 007 ...