开发者

test if a string is a number

How to test开发者_Go百科 if a string is composed only of digits ?


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).


For example, using the re module:

1> re:run("1234a56", "^[0-9]*$").
nomatch
2> re:run("123456", "^[0-9]*$"). 
{match,[{0,6}]}

Or, using list comprehension:

[Char || Char <- String, Char < $0 orelse Char > $9] == [].

Note that both solutions will consider the empty list valid input.


Use a regular expression.


not lists:any(fun(C)->C < $0 or C > $9 end, YourString).

In production, though, I would agree with the list_to_integer as it's probably better optimized. I'm not sure whether there are different traversal characteristics on 'any' vs 'all' either - you could implement each of them in terms of the other, but they're probably both implemented in C.


Erlang doesn't come with a way to say if a string represents a numeric value or not, but does come with the built-in function is_number/1, which will return true if the argument passed is either an integer or a float. Erlang also has two functions to transform a string to either a floating number or an integer, which will be used in conjunction with is_number/1.

is_numeric(L) ->
    Float = (catch erlang:list_to_float(L)),
    Int = (catch erlang:list_to_integer(L)),
    is_number(Float) orelse is_number(Int).

https://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Erlang

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜