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

时间:2010-12-01 20:22:55

标签: string erlang floating-point integer

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

<<"5.7778345">>

<<"444555">>

我事先不知道它是浮点数还是整数。

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

它必须是

等功能
binToNumber(Bin) ->
  %%Find if int or float
  Return.

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

所有最好的

4 个答案:

答案 0 :(得分: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.

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

答案 1 :(得分: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.

答案 2 :(得分:0)

似乎不需要中间转换为列表:

-spec binary_to_number(binary()) -> float() | integer().
binary_to_number(B) ->
    try binary_to_float(B)
    catch
        error:badarg -> binary_to_integer(B)
    end.

答案 3 :(得分:-1)

binary_to_term函数及其对应term_to_binary可能对您有用。

相关问题