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".
There are 2 ways to format a string in Julia. Printf is a standard library in Julia that is included by following the syntax: Julia uses printf () function similar to C, in order to format strings. Here, we print using the macro @printf.
The default type for an integer literal depends on whether the target system has a 32-bit architecture or a 64-bit architecture: The Julia internal variable Sys.WORD_SIZE indicates whether the target system is 32-bit or 64-bit:
The following are Julia's primitive numeric types: Integer types: Type Signed? Number of bits Smallest value Largest value Int8 ✓ 8 -2^7 2^7 - 1 UInt8 8 0 2^8 - 1 Int16 ✓ 16 -2^15 2^15 - 1 UInt16 16 0 2^16 - 1 7 more rows ...
In Julia, there are format specifiers somewhat similar to C: %c: a single character (letter, number, special symbol) %s: string (a combination of characters) %d: integer (any whole number (not a fraction))
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With