Add Decimal.from_any/1 function to handle int, float, and binary input#116
Conversation
| """ | ||
| @spec from_any(number | binary) :: t | ||
| def from_any(float) when is_float(float), do: from_float(float) | ||
| def from_any(value), do: new(value) |
There was a problem hiding this comment.
Thanks for the PR!
because we use Decimal.new under the hood, this will work too:
iex> Decimal.from_any(Decimal.new(42))
#Decimal<42>Could you send another patch with an update to docs and specs to mention we accept decimals here too? Theres a decimal :: t | integer | String.t type that you can use.
There was a problem hiding this comment.
Thanks, this will be a big help for us. And I'd be happy to submit that update as well, good call!
|
I'd like to revisit the name of this function. The problem is it doesn't really work with any type, just a small subset of types, so by calling it Here's a couple ideas:
I personally like the 1st option the most. What do you think? |
|
Happy to revisit the name! I really like Here's more detail on why I prefer it to the others:
|
We've had issues with warnings from passing a float to
Decimal.new/1in some of the 1,000+ calls in our production Elixir application, since sometimes we want to create a Decimal without knowing the type we're passing in ahead of time.We created this new function to handle that scenario in our app, then realized it might be better as part of the public interface of this library. Since float conversion is not exact, its module doc encourages people to use
Decimal.new/1orDecimal.from_float/1instead whenever possible.We also noticed that Ecto implemented a
decimal_new/1to workaround these same warnings, so if this is added to Decimal, it could be used instead of that work-around in Ecto:https://github.com/elixir-ecto/ecto/blob/6bc632e90f0639e4643c77e599b357dac2a9acb4/lib/ecto/changeset.ex#L2047
And it would more explicitly allow for the functionality requested in this earlier PR: #109
Thanks for your consideration!