ERLANG - binary string to integer or float

◇◆丶佛笑我妖孽 提交于 2020-06-24 12:01:27

问题


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. Does not work since it is binary. And tried converting binary to list then check if int or float. Not 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?

All the Best


回答1:


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.




回答2:


This is the pattern that we use:

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.



回答3:


Intermediate conversion to list is unnecessary since Erlang/OTP R16B:

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



回答4:


The binary_to_term function and its counterpart term_to_binary would probably serve you well.



来源:https://stackoverflow.com/questions/4328719/erlang-binary-string-to-integer-or-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!