[erlang-questions] io:format printing integers prefixed with zero(0)

Bob Ippolito <>
Mon May 5 18:19:02 CEST 2008


I just happened to have written a string formatting library yesterday,
modeled after Python 2.6's PEP 3101 Advanced String Formatting. it's
in the mochiweb repository here:
http://mochiweb.googlecode.com/svn/trunk/src/mochifmt.erl

Basically:

> lists:flatten(mochifmt:format("{0:03}", {3})).
"003"

Or since it's just one number:

> lists:flatten(mochifmt:format_field(3, "03")).
"003"

If you need a list rather than an iolist you can use:

> mochifmt:f("{0:03}", {3}).
"003"

Similarly, bformat is the same as format but it gives you a binary
(just using iolist_to_binary).

On Mon, May 5, 2008 at 2:17 AM, Peter Lund <> wrote:
> or:
>
>  1> string:right(integer_to_list(3),3,$0).
>  "003"
>  2> string:right(integer_to_list(50),3,$0).
>  "050"
>  3> string:right(integer_to_list(205),3,$0).
>  "205"
>  4> string:right(integer_to_list(33205),3,$0).
>  "205"
>
>  does almost the same...
>
>  Michael McDaniel skrev:
>
>
> > On Sat, May 03, 2008 at 02:51:33PM +1000, jm wrote:
>  >
>  >> Given an integer is there a format which will prefix it with zeros to a
>  >>   fixed width? eg,
>  >>
>  >>    3 => 003
>  >>   50 => 050
>  >> 205 => 205
>  >>
>  >> the equivelant of C's printf("%3.3d", i).
>  >>
>  >>
>  >> Jeff.
>  >> _______________________________________________
>  >>
>  >
>  >
>  >
>  > ()40> io:fwrite("~3.3.0w ", [1]).
>  > 001 ok
>  > ()41> io:fwrite("~3.3.0w ", [10]).
>  > 010 ok
>  > ()42> io:fwrite("~3.3.0w ", [100]).
>  > 100 ok
>  > ()43>
>  >
>  >
>  >  see io docs; file:///usr/local/lib/erlang/lib/stdlib-1.15/doc/html/io.html
>  >  on my system
>  >
>  >
>  > ~Michael
>  > _______________________________________________
>  > erlang-questions mailing list
>  > 
>  > http://www.erlang.org/mailman/listinfo/erlang-questions
>  >
>  >
>
>  _______________________________________________
>  erlang-questions mailing list
>  
>  http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list