Skip to content

Commit cd6aa59

Browse files
committed
Update custom JSON encoder example
Ref: #220
1 parent c9347ed commit cd6aa59

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

lib/decimal.ex

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,16 +69,19 @@ defmodule Decimal do
6969
7070
iex> encoder = fn
7171
...> %Decimal{} = decimal, _encoder ->
72-
...> decimal |> Decimal.to_float() |> :json.encode_float()
72+
...> if Decimal.inf?(decimal) or Decimal.nan?(decimal) do
73+
...> raise ArgumentError, "\#{inspect(decimal)} cannot be encoded to JSON"
74+
...> end
75+
...>
76+
...> Decimal.to_string(decimal)
7377
...>
7478
...> other, encoder ->
7579
...> JSON.protocol_encode(other, encoder)
7680
...> end
7781
...>
7882
iex> JSON.encode!(%{x: Decimal.new("1.00")}, encoder)
79-
"{\\"x\\":1.0}"
83+
"{\\"x\\":1.00}"
8084
81-
Note: `Decimal.to_float/1` crashes on infinite and NaN decimals.
8285
"""
8386

8487
import Bitwise

test/decimal_test.exs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -995,7 +995,11 @@ defmodule DecimalTest do
995995

996996
encoder = fn
997997
%Decimal{} = decimal, _encode ->
998-
decimal |> Decimal.to_float() |> :json.encode_float()
998+
if Decimal.inf?(decimal) or Decimal.nan?(decimal) do
999+
raise ArgumentError, "#{inspect(decimal)} cannot be encoded to JSON"
1000+
end
1001+
1002+
Decimal.to_string(decimal)
9991003

10001004
other, encode ->
10011005
JSON.protocol_encode(other, encode)

0 commit comments

Comments
 (0)