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?
String s=((Integer)i). toString(); Demo.
12.3) Strings in Elixir are UTF-8 encoded binaries. Strings in Elixir are a sequence of Unicode characters, typically written between double quoted strings, such as "hello" and "héllò" .
You can use String.pad_leading/3
my_count |> Integer.to_string |> String.pad_leading(3, "0")
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
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