I need a function that takes a Decimal
(it’s money, so two decimal places) and rounds up to the nearest quarter. I’m trying to avoid converting to floats and staying within the Decimal world.
This function works, but it is hideous. The decimal library only natively supports rounding to the whole or half, and I can’t slip values like :lt
and :gt
into Enum.member?
because they are not enumerable, so I used separate conditions for :lt
and :gt
.
def round_up_to_nearest_quarter(preroundedamount) do
alias Decimal, as: D
base = D.round(preroundedamount, 0, :floor)
frac = D.sub(preroundedamount, base)
newfrac =
cond do
D.cmp(frac, 0) == :eq ->
D.new("0.0")
D.cmp(frac, D.new("0.25")) == :lt ->
D.new("0.25")
D.cmp(frac, D.new("0.25")) == :eq ->
D.new("0.25")
D.cmp(frac, D.new("0.5")) == :lt ->
D.new("0.5")
D.cmp(frac, D.new("0.5")) == :eq ->
D.new("0.5")
D.cmp(frac, D.new("0.75")) == :lt ->
D.new("0.75")
D.cmp(frac, D.new("0.75")) == :eq ->
D.new("0.75")
D.cmp(frac, D.new("1.0")) == :lt ->
D.new("1.0")
D.cmp(frac, D.new("1.0")) == :eq ->
D.new("1.0")
true ->
D.new("0.0")
end
D.add(base, newfrac)
end
What is the most Elixir-ian** way to do this?
**Also, what is the adjective form of “Elixir”? Looking for something like “Pythonic”.