How to convert an integer to a string in Erlang?

StringErlang

String Problem Overview


I know strings in Erlang can be costly to use. So how do I convert "5"to 5?

Is there anything like io:format("~p",[5]) that would return a formatted string instead of printing to a stream?

String Solutions


Solution 1 - String

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

Solution 2 - String

A string is a list:

9> integer_to_list(123).  
"123"

Solution 3 - String

The following is probably not the neatest way, but it works:

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

EDIT: I've found that the following function comes in useful:

%% 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 I wrote a while back to learn Erlang. I was looking for a string-formatting function and found the behaviour of io_lib:format/2 within erl counter-intuitive, for example:

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

At the time, I was unaware of the 'auto-flattening' behaviour of output devices mentioned by @archaelus and so concluded that the above behaviour wasn't what I wanted.

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

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

Solution 4 - String

As an aside if you ever need to deal with the string representation of floats you should look at the work that Bob Ippolito has done on mochinum.

Solution 5 - String

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncollapsinghrungView Question on Stackoverflow
Solution 1 - StringwombleView Answer on Stackoverflow
Solution 2 - StringThomasView Answer on Stackoverflow
Solution 3 - StringLuke WoodwardView Answer on Stackoverflow
Solution 4 - StringGordon GuthrieView Answer on Stackoverflow
Solution 5 - StringMichael NealeView Answer on Stackoverflow