ewildgoose / elixir-xml_rpc

Encode and decode elixir terms to XML-RPC parameters
Apache License 2.0
40 stars 17 forks source link

Bugfix/incorrect float to binary convert #15

Closed EevanW closed 5 years ago

EevanW commented 5 years ago

When we converting float to string, we can see repeating decimal there should be a fixed number of characters after point (128.39 -> "128.38999999999999"). For example:

iex(1)>  %XMLRPC.MethodCall{method_name: "test", params: [127.39]} |> XMLRPC.encode!  
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>test</methodName><params><param><value><double>127.39</double></value></param></params></methodCall>"
iex(2)>  %XMLRPC.MethodCall{method_name: "test", params: [128.39]} |> XMLRPC.encode!  
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>test</methodName><params><param><value><double>128.38999999999999</double></value></param></params></methodCall>"

The problem lies in the declared accuracy of calculations :erlang.float_to_binary This problem can be solved by using [options] as parameter of encoding/2 function.

For example:

iex(3)>  %XMLRPC.MethodCall{method_name: "test", params: [128.39]} |> XMLRPC.encode!(decimals: 2)  
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>test</methodName><params><param><value><double>128.39</double></value></param></params></methodCall>"

or

iex(4)>  %XMLRPC.MethodCall{method_name: "test", params: [128.39]} |> XMLRPC.encode!([decimals: 2])  
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>test</methodName><params><param><value><double>128.39</double></value></param></params></methodCall>"
EevanW commented 5 years ago

It's generic solution.