Convert integer to string in Erlang

I know Erlang strings should be avoided at all costs ...

but if I do not, how can I create a “5” from 5?

in particular, is there something like io: format ("~ p", [5]) that will return a formatted string instead of printing to a stream?

+48
string erlang
Feb 25 '09 at 21:38
source share
5 answers

This may not be the easiest way, but it works:

1> lists:flatten(io_lib:format("~p", [35365])). "35365" 

EDIT: I found that a useful feature:

 %% string_format/2 %% Like io:format except it returns the evaluated string rather than write %% it to standard output. %% Parameters: %% 1. format string similar to that used by io:format. %% 2. list of values to supply to format string. %% Returns: %% Formatted string. string_format(Pattern, Values) -> lists:flatten(io_lib:format(Pattern, Values)). 

EDIT 2 (in response to comments): The above function came from a small program that I wrote some time ago to learn Erlang. I was looking for a string formatting function and found the io_lib:format/2 behavior inside erl counter-intuitive, for example:

 1> io_lib:format("2 + 2 = ~p", [2+2]). [50,32,43,32,50,32,61,32,"4"] 

At that time, I did not know about the "automatic alignment" of the behavior of the output devices mentioned by @archaelus, and therefore came to the conclusion that the above behavior was not what I wanted.

This evening I returned to this program and replaced the calls with the string_format function above using io_lib:format . The only problems that caused this were a few EUnit tests that failed because they were expecting a flattened string. They were easily fixed.

I agree with @gleber and @womble that using this function is redundant to convert an integer to a string. If that's all you need, use integer_to_list/1 . KISS!

+10
Feb 25 '09 at 21:48
source share

There's also integer_to_list/1 , which does exactly what you want, without ugliness.

+131
Feb 25 '09 at 10:40
source share

The string is a list:

 9> integer_to_list(123). "123" 
+24
Oct 29 '09 at 19:24
source share

As an aside, if you ever need a string representation of floats, you should look at the work that Bob Ippolito mochinum did .

+4
Feb 26 '09 at 9:46
source share

lists: CONCAT ([Number]). also works.

+2
Mar 09 2018-11-11T00:
source share



All Articles