Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/quantity.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ defmodule Quantity.MixProject do
[
# Decimal
{:decimal, "~> 2.0"},
{:jason, "~> 1.4"},

# Documentation
{:ex_doc, "~> 0.21", only: :dev, runtime: false},
Expand Down
4 changes: 4 additions & 0 deletions test/quantity_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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 ->
Expand Down