Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing from_decimal and to_decimal #120

Closed
strzibny opened this issue Dec 5, 2019 · 4 comments · Fixed by #121
Closed

Implementing from_decimal and to_decimal #120

strzibny opened this issue Dec 5, 2019 · 4 comments · Fixed by #121

Comments

@strzibny
Copy link
Contributor

strzibny commented Dec 5, 2019

I think it would be nice and beneficial if there could be a way to accept Decimal on both input and provide on the output side. Many applications might be working or getting decimals and if then we want to use the money library it's kind of cumbersome. What do you think?

@Nitrino
Copy link
Member

Nitrino commented Dec 5, 2019

Hi @strzibny,

I think this is a great idea.
For input values, I think we can expand the capabilities of the parse function, now supported strings and floats.

Workaround for current functionality:

iex(7)> Decimal.cast(2.5) |> Decimal.to_float() |> Money.parse!()
%Money{amount: 250, currency: :USD}

I think to_decimal is a good name for the conversion function.

If you want to contribute, pull requests are welcome.

@strzibny
Copy link
Contributor Author

strzibny commented Dec 6, 2019

Do you think that something like the following is fine for the reverse?

money_str = Money.to_string(money, separator: "", delimiter: ".", symbol: false)
{:ok, decimal} = Decimal.parse(money_str)

@Nitrino
Copy link
Member

Nitrino commented Dec 6, 2019

It's a working option, but it's better to work with numbers.

iex(17)> price = Money.new(25, :USD)
%Money{amount: 25, currency: :USD}
iex(18)> price_in_float = price.amount / Money.Currency.sub_units_count!(price)
0.25
iex(19)> Decimal.from_float(price_in_float)
#Decimal<0.25>

This will give the same result, but it will avoid unnecessary conversions and the math will not depend on formatting settings.

@strzibny
Copy link
Contributor Author

strzibny commented Dec 9, 2019

@Nitrino yes, that would work better :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants