In Elixir, how do you format numbers with string interpolation

20,636

Solution 1

You can use String.pad_leading/3

my_count
|> Integer.to_string
|> String.pad_leading(3, "0")

Solution 2

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

Solution 3

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.

Share:
20,636
Matt
Author by

Matt

I'm just some guy who does some programming stuff.

Updated on June 04, 2020

Comments

  • Matt
    Matt almost 4 years

    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?

  • Luke Imhoff
    Luke Imhoff about 8 years
    Something that tripped me up was that :io.format outputs the formatted string to the group leader and returns :ok. If you need to capture the string before output or are just looking for something like sprintf, you want :io_lib.format, which will return a binary / Elixir String.t
  • nhooyr
    nhooyr almost 7 years
    I think it would be more clear to use String.pad_leading(3, "0").
  • apelsinka223
    apelsinka223 over 6 years
    rjust is deprecated
  • ilyak
    ilyak over 6 years
    io_lib.format returns a list of chars rather than a binary