e r l a n g : c o o k b o o k

/ Erlang.StringNumber

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Testing Whether a String Represents an Integer

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

Discussion

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
-- PhilipRobinson - 15 Jun 2006

Contributors

Based on work by GordonWeakliem and NoelWelsh.

-- BrentAFulgham - 23 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: StringRecipes
TopicOrder: 200

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest