Merge pull request #7993 from EMQ-YangM/add_func_float2str

feat: add rule engine function float2str/2
This commit is contained in:
Yang Miao 2022-05-19 17:07:35 +08:00 committed by GitHub
commit c91dff349a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 13 additions and 0 deletions

View File

@ -39,6 +39,7 @@
bool/1, bool/1,
int/1, int/1,
float/1, float/1,
float2str/2,
map/1, map/1,
utf8_bin/1, utf8_bin/1,
utf8_str/1, utf8_str/1,
@ -258,6 +259,9 @@ float(Num) when is_number(Num) -> erlang:float(Num);
float(Data) -> float(Data) ->
error({invalid_number, Data}). error({invalid_number, Data}).
float2str(Float, Precision) when is_float(Float) and is_integer(Precision) ->
float_to_binary(Float, [{decimals, Precision}, compact]).
map(Bin) when is_binary(Bin) -> map(Bin) when is_binary(Bin) ->
case emqx_json:decode(Bin, [return_maps]) of case emqx_json:decode(Bin, [return_maps]) of
Map = #{} -> Map; Map = #{} -> Map;

View File

@ -103,6 +103,7 @@
int/1, int/1,
float/1, float/1,
float/2, float/2,
float2str/2,
map/1, map/1,
bin2hexstr/1, bin2hexstr/1,
hexstr2bin/1 hexstr2bin/1
@ -616,6 +617,9 @@ float(Data, Decimals) when Decimals > 0 ->
Data1 = ?MODULE:float(Data), Data1 = ?MODULE:float(Data),
list_to_float(float_to_list(Data1, [{decimals, Decimals}])). list_to_float(float_to_list(Data1, [{decimals, Decimals}])).
float2str(Float, Precision) ->
emqx_plugin_libs_rule:float2str(Float, Precision).
map(Data) -> map(Data) ->
emqx_plugin_libs_rule:map(Data). emqx_plugin_libs_rule:map(Data).

View File

@ -169,6 +169,11 @@ t_term_encode(_) ->
end, end,
TestData TestData
). ).
t_float2str(_) ->
?assertEqual(<<"20.2">>, emqx_rule_funcs:float2str(20.2, 1)),
?assertEqual(<<"20.2">>, emqx_rule_funcs:float2str(20.2, 10)),
?assertEqual(<<"20.199999999999999">>, emqx_rule_funcs:float2str(20.2, 15)),
?assertEqual(<<"20.1999999999999993">>, emqx_rule_funcs:float2str(20.2, 16)).
t_hexstr2bin(_) -> t_hexstr2bin(_) ->
?assertEqual(<<6, 54, 79>>, emqx_rule_funcs:hexstr2bin(<<"6364f">>)), ?assertEqual(<<6, 54, 79>>, emqx_rule_funcs:hexstr2bin(<<"6364f">>)),