Skip to content

Commit 47553f9

Browse files
authored
Decode integer-formatted JSON numbers as float (#364) (#385)
1 parent 27c5716 commit 47553f9

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

lib/protobuf/json/decode.ex

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,7 @@ defmodule Protobuf.JSON.Decode do
392392
end
393393

394394
defp decode_float(float) when is_float(float), do: {:ok, float}
395+
defp decode_float(integer) when is_integer(integer), do: {:ok, integer / 1}
395396
defp decode_float(string) when is_binary(string), do: parse_float(string)
396397
defp decode_float(_bad), do: :error
397398

test/protobuf/json/decode_test.exs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,10 @@ defmodule Protobuf.JSON.DecodeTest do
238238
data = %{"float" => 1.23e3, "double" => 1.23e-2}
239239
decoded = %Scalars{float: 1230.0, double: 0.0123}
240240
assert decode(data, Scalars) == {:ok, decoded}
241+
242+
data = %{"float" => 5, "double" => 9}
243+
decoded = %Scalars{float: 5.0, double: 9.0}
244+
assert decode(data, Scalars) == {:ok, decoded}
241245
end
242246

243247
test "constants are valid" do
@@ -279,8 +283,8 @@ defmodule Protobuf.JSON.DecodeTest do
279283
end
280284

281285
test "other types are invalid" do
282-
data = %{"float" => 5}
283-
msg = "Field 'float' has an invalid floating point (5)"
286+
data = %{"float" => <<1::15>>}
287+
msg = "Field 'float' has an invalid floating point (<<0, 1::size(7)>>)"
284288
assert decode(data, Scalars) == error(msg)
285289

286290
data = %{"double" => true}

0 commit comments

Comments
 (0)