ERLANG-二进制字符串为整数或浮点型 [英] ERLANG - binary string to integer or float

查看:114
本文介绍了ERLANG-二进制字符串为整数或浮点型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have binary strings in the form of either:

<<"5.7778345">>

<<"444555">>

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

I do not know before hand whether it will be a float or integer.

我尝试检查一下是否为整数。由于它是二进制文件,因此不起作用。并尝试将二进制转换为列表,然后检查int或float。

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.

它必须是诸如

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

每个人都有一个很好的主意吗?

Anyone have a good idea of how to do this?

一切顺利

推荐答案

没有快速的方法。改用类似这样的东西:

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.

这篇关于ERLANG-二进制字符串为整数或浮点型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆