Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Elixir, how do you format numbers with string interpolation

Tags:

elixir

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?

like image 892
Matt Avatar asked Dec 18 '15 14:12

Matt


People also ask

How do you convert int to string in Elixir?

String s=((Integer)i). toString(); Demo.

Is Elixir a string?

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


2 Answers

You can use String.pad_leading/3

my_count |> Integer.to_string |> String.pad_leading(3, "0") 
like image 86
Dmitry Biletskyy Avatar answered Oct 10 '22 12:10

Dmitry Biletskyy


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 
like image 30
Simone Carletti Avatar answered Oct 10 '22 12:10

Simone Carletti