Reputation: 88027
I want to print out a string like
IO.puts("Count: #{my_count}")
But I want leading zeroes in the output like
Count: 006
How do I do that and where is that documentation?
Upvotes: 46
Views: 27637
Reputation: 1903
You can use String.pad_leading/3
my_count
|> Integer.to_string
|> String.pad_leading(3, "0")
Upvotes: 71
Reputation: 5138
You can also use String.pad_leading/3:
my_count
|> Integer.to_string
|> String.pad_leading(3, "0")
Note that the release note of v1.3.0 says:
The confusing String.ljust/3 and String.rjust/3 API has been soft deprecated in favor of String.pad_leading/3 and String.pad_trailing/3
This is a soft deprecation. Its use does not emit warnings.
Upvotes: 14
Reputation: 176352
I'm not sure there is an integer-to-string with padding formatter method in Elixir. However, you can rely on the Erlang io
module which is accessible in Elixir with the :io
atom.
iex(1)> :io.format "~3..0B", [6]
006:ok
You can find an explanation in this answer. I'm quoting it here for convenience:
"~3..0B"
translates to:~F. = ~3. (Field width of 3) P. = . (no Precision specified) Pad = 0 (Pad with zeroes) Mod = (no control sequence Modifier specified) C = B (Control sequence B = integer in default base 10)
You can either use it directly, or wrap it in a custom function.
iex(5)> :io.format "Count: ~3..0B", [6]
Count: 006:ok
Upvotes: 25