[erlang-questions] convert strings like "1e-8" to floats.

Per Hedeland per@REDACTED
Tue Feb 7 17:13:42 CET 2017


On 2017-02-07 10:54, Oleksii Semilietov wrote:
> 
> I playing with converting binaries and lists to floats and I found
> something what I can't solve via elegant way. I believe it's my leakage of
> understanding floats.

No, I think it's just that Erlang is a bit more, uh, pedantic than other
languages about what the "good representation" of a float is.

> But when floats coming from external world as binaries or lists which looks
> like "1e-8", and not like "1.0e-8", I can't find proper way to convert it.

I don't know if there is a "proper" way, but something like this should
do the trick:

tolerant_list_to_float(L) ->
    case re:run(L, "^([+-]?\\d+)([Ee]\\d+)?$", [{capture, [1, 2], list}]) of
        {match, [M, E]} ->
            list_to_float(M ++ ".0" ++ E);
        _ ->
            list_to_float(L)
    end.

--Per



More information about the erlang-questions mailing list