Last active
February 10, 2022 03:28
-
-
Save trbngr/c9f0abd70de440b639d18efa8b686119 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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