File tree Expand file tree Collapse file tree 2 files changed +11
-4
lines changed
Expand file tree Collapse file tree 2 files changed +11
-4
lines changed Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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 )
You can’t perform that action at this time.
0 commit comments