How to convert a binary string to an integer or a float?

后端 未结 4 1768
梦谈多话
梦谈多话 2021-02-08 01:56

I have binary strings in the form of either:

<<"5.7778345">>

or

<<"444555">>
         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-08 02:25

    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.

提交回复
热议问题