From 55a07b9923dec20b0ffc2441b85f2ec808f4aee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Viktor=20S=C3=B6derqvist?= Date: Thu, 9 Mar 2023 10:14:54 +0100 Subject: [PATCH] Parse floats with exponent part, without decimal fraction part Erlang is odd here, since Erlang requires a decimal fraction part (i.e. a dot followed by digits). The number "1e100" needs to be rewritten to "1.0e100" before parsing it using binary_to_float/1. --- src/ered_parser.erl | 10 ++++++++-- test/ered_parser_tests.erl | 4 ++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/ered_parser.erl b/src/ered_parser.erl index b866fba..9142aba 100644 --- a/src/ered_parser.erl +++ b/src/ered_parser.erl @@ -148,8 +148,14 @@ parse_float(Data) -> try binary_to_float(Data) catch error:badarg -> - %% maybe its a float without decimal - try float(binary_to_integer(Data)) + %% maybe its a float without decimal fractions + try + case binary:split(Data, [<<"E">>, <<"e">>]) of + [Integer, Exponent] -> + binary_to_float(<>); + [Integer] -> + float(binary_to_integer(Integer)) + end catch error:badarg -> throw({parse_error, {not_float, Data}}) end diff --git a/test/ered_parser_tests.erl b/test/ered_parser_tests.erl index 18ea044..3b063b9 100644 --- a/test/ered_parser_tests.erl +++ b/test/ered_parser_tests.erl @@ -57,6 +57,10 @@ test_data() -> {"streamed map", <<"%?\r\n+a\r\n:1\r\n+b\r\n:2\r\n.\r\n">>, #{<<"a">> => 1, <<"b">> => 2}}, %% Additional tests {"streamed set", <<"~?\r\n+a\r\n:1\r\n+b\r\n:2\r\n.\r\n">>, set_from_list([<<"a">>, 1, <<"b">>, 2])}, + {"float exponent", <<",1.1e100\r\n">>, 1.1e100}, + {"float exponent no fractions", <<",4e100\r\n">>, 4.0e100}, + {"float +exponent no fractions", <<",4e+100\r\n">>, 4.0e100}, + {"float -exponent no fractions", <<",4e-100\r\n">>, 4.0e-100}, {"float negative", <<",-1.23\r\n">>, -1.23} ].