Skip to content

Instantly share code, notes, and snippets.

@trbngr
Last active February 10, 2022 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trbngr/c9f0abd70de440b639d18efa8b686119 to your computer and use it in GitHub Desktop.
Save trbngr/c9f0abd70de440b639d18efa8b686119 to your computer and use it in GitHub Desktop.
Mix.install([:decimal])
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))
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
use 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])
:tiddies
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment