ericmj / decimal

Arbitrary precision decimal arithmetic

Home Page:https://hexdocs.pm/decimal/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Proposal to add helpers

starbelly opened this issue · comments

Often times I end up writing helper functions to go along with Decimal, so much so that I'm proposing to add these helpers to Decimal. The code is of course trivial, every helper definition is a one liner. Arguably, that makes a good case for not putting them in Decimal. None the less, I feel like they would make a good additional and prove to be useful.

Comparison helpers

Operation that uses Decimal.cmp/2 to determine if one value is eq or gt than another

def foo(a,b) do
   Decimal.cmp(a,b) in [:eq, :gt]
end 

An improvement using a helper function

def foo(a, b) do 
  Decimal.gt_or_eq?(a,b)
end

The following comparison helpers are suggested

  • lt/2 or lt?/2
  • gt/2 or gt?/2
  • eq/2 or eq?/2
  • neq/2 or neq?/2
  • gt_or_eq/2 or gt_or_eq?/2
  • lt_or_eq/2 or lt_or_eq?/2

Other binary operation helpers

The following helpers would take two decimals, a places value, and optionally a rounding method defaulting to :half_up.

Without helper

def foo(a,b) do 
  Decimal.round(Decimal.div(a, b), 2)
end

def bar(a,b) do 
 Decimal.round(Decimal.add(a, b), 2, :half_up)
end

With helpers:

def foo(a,b) do 
  Decimal.add_round(a, b, 2)
end

def bar(a,b) do 
  Decimal.mult_round(a, b, 5, :half_down) 
end
  • div_round/3 and div_round/4
  • add_round/3 and add_round/4
  • mult_round/3 and mult_round/4

Misc. helpers

  • as_negative/1 - takes a decimal and multiplies by -1

Thanks for the proposals, I am going to respond for each section.

Comparison helpers

I think we can start with lt?/2, gt?/2, eq?/2. neq?/2 only saves a few characters. Not sure about gt_or_eq?/2 and lt_or_eq?/2, I think we can hold off on those for now and maybe them later.

Other binary operation helpers

I don't think any of those are needed because you should probably be configuring the context to round down to your maximum precision instead. The other issue is that _round could be added to every arithmetic operation, so we would be adding a lot of extra functions.

Misc. helpers

as_negative/1 sounds good, but the name is a bit confusing to me. Is it supposed to make the number negative or supposed to multiply by -1, because those are different operations? If only multiplying by -1 then I think negate/1 would be a more clear name.

I hear you on the _round arguments and agree.

lt?/2, gt?/2, eq?/2 so these are wanted?. The main idea and I didn't have it in the examples was to use them for logic (i.e., this and that or (foo and bar)), but you're right, in the end this only saves characters so now I'm a bit unsure 🤔

Also, negate/1 sounds good.

lt?/2, gt?/2, eq?/2 so these are wanted?

Yes

Closing in favour of PR.