Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test if a string is a number

Tags:

erlang

How to test if a string is composed only of digits ?

like image 653
Bertaud Avatar asked Dec 09 '22 11:12

Bertaud


1 Answers

One way is to convert it to an integer and if that fails then you'll know it's not an integer.

is_integer(S) ->
    try
        _ = list_to_integer(S),
        true
    catch error:badarg ->
        false
    end.

Or you can just check all of the digits, but you do have to check the edge case of an empty list:

is_integer("") ->
    false;
is_integer(S) ->
    lists:all(fun (D) -> D >= $0 andalso D =< $9 end, S).
like image 109
YOUR ARGUMENT IS VALID Avatar answered Dec 20 '22 06:12

YOUR ARGUMENT IS VALID