Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format an integer with zero padding in Julia?

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".

like image 615
DVNold Avatar asked Jan 15 '21 14:01

DVNold


People also ask

How to format a string in Julia?

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.

What is the default type for an integer literal in Julia?

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:

What are the primitive numeric types available in Julia?

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 ...

What are the format specifiers in Julia?

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))


Video Answer


3 Answers

julia> string(123, pad=6)
"000123"
like image 146
MarcMush Avatar answered Oct 22 '22 17:10

MarcMush


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.

like image 39
Nathan Boyer Avatar answered Oct 22 '22 17:10

Nathan Boyer


There are lpad and rpad functions.

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

julia> lpad(1234567, 6, '0')
"1234567"
like image 2
Andrej Oskin Avatar answered Oct 22 '22 17:10

Andrej Oskin