Erlang Central

Difference between revisions of "String Is Integer"

From ErlangCentral Wiki

m
Line 44:Line 44:
  
 
[[Category:CookBook]][[Category:StringRecipes]][[Category:NumberRecipes]]
 
[[Category:CookBook]][[Category:StringRecipes]][[Category:NumberRecipes]]
 +
 +
 +
 +
[http://www.slots-wiki.com/index.php/slots_online slots online]
 +
[http://www.slots-wiki.com/index.php/slots slots]
 +
[http://www.online-casino-wiki.com/index.php/online_casino online casino]
 +
[http://www.gambling-online-theory.com/online-casino/online-casino-for-cash.html online casino for cash]
 +
[http://www.casino-theory.com/online-casino-bonus/online-casino-net.html online casino net]
 +
[http://www.slots-wiki.com/index.php/online_slots online slots]
 +
[http://www.bestweb-online-casinos.com/slots-game/diamond-club-slots.html diamond club slots]
 +
[http://www.slots-wiki.com/index.php/slots_online slots online]
 +
[http://www.web-craps.com craps]
 +
[http://www.magical-casino.com/casino_risk.html Gambling Online - Risks.]

Revision as of 04:03, 4 December 2006

Problem

You want to determine whether a string is an integer

Solution

The io_lib:fread function is the easiest method. io_lib:fread can handle strings containing base 2 through 36 numbers into a number, though decimal is the default. If the conversion can't be performed, or if the string does not contain a number, io_lib:fread returns {error} (rather than {ok}. Here are some examples showing the proper format specifiers:

1> io_lib:fread("~d", "1234").
{ok,[1234],[]}
2> io_lib:fread("~16u", "abc").
{ok,[2748],[]}
3> io_lib:fread("~d", "abc").
{error,{fread,integer}}

This is only half the solution, however. io_lib:fread works for any kind of number, so technically, you should wrap the call in a call to the is_integer predicate:

4> Is_String_Int = fun(String) ->
4>     {ok,IntString,Stuff} = io_lib:fread("~d", String),
4>     IntStringHead = hd(IntString),
4>     is_integer(IntStringHead)
4> end.
#Fun<erl_eval.6.39074546>
5> Is_String_Int("77").
true

Even this function is not perfect. It thinks "77.7" is an integer since it reads the 77 and drops the .7 prior to trying the is_integer predicate. Need to research this a bit more.

Is there a reason why the list_to_integer function is not used for this?

1> Is_String_Int = fun(String) ->
1>     case (catch list_to_integer(String)) of
1>         {'EXIT', _} -> false;
1>         Integer -> true
1>     end
1> end.
#Fun<erl_eval.6.56006484>
2> Is_String_Int("77.7").
false
3> Is_String_Int("77").
true


slots online slots online casino online casino for cash online casino net online slots diamond club slots slots online craps Gambling Online - Risks.