ERLANG - 二进制字符串到整数或浮点数

BAR*_*BAR 8 string floating-point erlang integer

我有两种形式的二进制字符串:

<<"5.7778345">>
Run Code Online (Sandbox Code Playgroud)

要么

<<"444555">>
Run Code Online (Sandbox Code Playgroud)

我不知道它是浮点数还是整数.

我试着检查它是否是一个整数.因为它是二进制的,所以不起作用.并尝试将二进制转换为列表然后检查int或float.没那么成功.

它需要是一个功能,如

binToNumber(Bin) ->
  %%Find if int or float
  Return.
Run Code Online (Sandbox Code Playgroud)

任何人都知道如何做到这一点?

祝一切顺利

I G*_*ICE 19

没有快速的方法来做到这一点.使用这样的东西代替:

bin_to_num(Bin) ->
    N = binary_to_list(Bin),
    case string:to_float(N) of
        {error,no_float} -> list_to_integer(N);
        {F,_Rest} -> F
    end.
Run Code Online (Sandbox Code Playgroud)

这应该将二进制文件转换为列表(字符串),然后尝试将其放入浮点数中.当无法完成时,我们返回一个整数.否则,我们保持浮动并返回.


YOU*_*LID 12

这是我们使用的模式:

binary_to_number(B) ->
    list_to_number(binary_to_list(B)).

list_to_number(L) ->
    try list_to_float(L)
    catch
        error:badarg ->
            list_to_integer(L)
    end.
Run Code Online (Sandbox Code Playgroud)