erlang 如何将二进制字符串转换为整数或浮点数?

rbpvctlc  于 2022-12-08  发布在  Erlang
关注(0)|答案(4)|浏览(178)

I have binary strings in the form of either:

<<"5.7778345">>

or

<<"444555">>

I do not know before hand whether it will be a float or integer.
I tried doing a check to see if it is an integer. This does not work since it is binary. I alos tried converting binary to list, then check if int or float. I did not have much success with that.
It needs to be a function such as:

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

Anyone have a good idea of how to do this?

daolsyd0

daolsyd01#

No quick way to do it. Use something like this instead:

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.

This should convert the binary to a list (string), then try to fit it in a float. When that can't be done, we return an integer. Otherwise, we keep the float and return that.

rjzwgtxy

rjzwgtxy2#

这是我们使用的模式:

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

qkf9rpyu3#

由于Erlang/OTP R16 B:

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

c9x0cxw04#

binary_to_term函数及其对应的term_to_binary可能会很好地为您服务。

相关问题