diff --git a/lib/quantity.ex b/lib/quantity.ex index 9d2e131..b81c198 100644 --- a/lib/quantity.ex +++ b/lib/quantity.ex @@ -146,7 +146,7 @@ defmodule Quantity do @doc """ Encodes the quantity as a string. The result is parsable with parse/1 - If the exponent is positive, encode usinge the "raw" format to preserve precision + If the exponent is positive, encode using the "raw" format to preserve precision iex> Quantity.new(42, -1, "db") |> Quantity.to_string() "4.2 db" @@ -351,6 +351,15 @@ defmodule Quantity do end end + defimpl Jason.Encoder do + @impl Jason.Encoder + def encode(value, opts) do + value + |> Quantity.to_string() + |> Jason.Encode.string(opts) + end + end + # Normalizes unit to a standard form: # * Shorten unit as much as possible # * At most one :div (with possibly many :mults on each side) diff --git a/mix.exs b/mix.exs index 3ffc5e8..42e5a75 100644 --- a/mix.exs +++ b/mix.exs @@ -36,6 +36,7 @@ defmodule Quantity.MixProject do [ # Decimal {:decimal, "~> 2.0"}, + {:jason, "~> 1.4"}, # Documentation {:ex_doc, "~> 0.21", only: :dev, runtime: false}, diff --git a/test/quantity_test.exs b/test/quantity_test.exs index 6c8a934..c708770 100644 --- a/test/quantity_test.exs +++ b/test/quantity_test.exs @@ -55,6 +55,10 @@ defmodule QuantityTest do assert Quantity.to_string(~Q[42]) == "42" end + test "encode to json from map" do + assert %{quantity: ~Q[12.45 DKK]} |> Jason.encode!() == ~S|{"quantity":"12.45 DKK"}| + end + test "for non-number decimals" do ["inf", "-inf", "nan"] |> Enum.each(fn not_number ->