Skip to content

Instantly share code, notes, and snippets.

@trbngr
Last active February 10, 2022 03:28
Show Gist options
  • Select an option

  • Save trbngr/c9f0abd70de440b639d18efa8b686119 to your computer and use it in GitHub Desktop.

Select an option

Save trbngr/c9f0abd70de440b639d18efa8b686119 to your computer and use it in GitHub Desktop.

Revisions

  1. trbngr revised this gist Feb 10, 2022. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion decimal_math.exs
    Original file line number Diff line number Diff line change
    @@ -36,6 +36,6 @@ defmodule Test do
    IO.inspect(10 * 12 / 365 * 5, label: "10 * 12 / 365 * 5")
    IO.inspect(10 * 12 / 365 * 5.0, label: "10 * 12 / 365 * 5.0")
    IO.inspect(10 * "12.0" / "365" * 5.0, label: ~s[10 * "12.0" / "365" * 5.0])
    :ok
    :tiddies
    end
    end
  2. trbngr revised this gist Feb 10, 2022. 1 changed file with 8 additions and 2 deletions.
    10 changes: 8 additions & 2 deletions decimal_math.exs
    Original file line number Diff line number Diff line change
    @@ -4,6 +4,13 @@ defmodule DecimalMath do
    alias Decimal, as: D
    import Decimal

    defmacro __using__(_opts) do
    quote do
    import Kernel, except: [*: 2, /: 2, +: 2, -: 2]
    import DecimalMath
    end
    end

    def left + right,
    do: D.add(dec(left), dec(right))

    @@ -23,8 +30,7 @@ defmodule DecimalMath do
    end

    defmodule Test do
    import Kernel, except: [*: 2, /: 2, +: 2, -: 2]
    import DecimalMath
    use DecimalMath

    def run do
    IO.inspect(10 * 12 / 365 * 5, label: "10 * 12 / 365 * 5")
  3. trbngr created this gist Feb 10, 2022.
    35 changes: 35 additions & 0 deletions decimal_math.exs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    Mix.install([:decimal])

    defmodule DecimalMath do
    alias Decimal, as: D
    import Decimal

    def left + right,
    do: D.add(dec(left), dec(right))

    def left - right,
    do: D.sub(dec(left), dec(right))

    def left * right,
    do: D.mult(dec(left), dec(right))

    def left / right,
    do: D.div(dec(left), dec(right))

    defp dec(value) when is_decimal(value), do: value
    defp dec(value) when is_float(value), do: Decimal.from_float(value)
    defp dec(value) when is_number(value), do: Decimal.new(value)
    defp dec(value) when is_binary(value), do: Decimal.new(value)
    end

    defmodule Test do
    import Kernel, except: [*: 2, /: 2, +: 2, -: 2]
    import DecimalMath

    def run do
    IO.inspect(10 * 12 / 365 * 5, label: "10 * 12 / 365 * 5")
    IO.inspect(10 * 12 / 365 * 5.0, label: "10 * 12 / 365 * 5.0")
    IO.inspect(10 * "12.0" / "365" * 5.0, label: ~s[10 * "12.0" / "365" * 5.0])
    :ok
    end
    end