elixirmoney / money

Elixir library for working with Money safer, easier, and fun... Is an interpretation of the Fowler's Money pattern in fun.prog.
https://hex.pm/packages/money/
MIT License
826 stars 139 forks source link

Money.parse doesn't handle scientific notation #216

Open nathany-copia opened 6 months ago

nathany-copia commented 6 months ago

I consider this a bug in our code, but I wanted to document it here, just so people are aware.

We had some code where Decimals were being represented in scientific notation, e.g.

value = Decimal.new("0")
divisor = :math.pow(10, 2) |> Decimal.from_float() # Decimal.new("100.0")
value = Decimal.div(value, divisor) # Decimal.new("0E+1")

That itself isn't a problem. The problem happens with some Money.parse code like this:

Money.parse!("#{value}", currency)

Which is effectively doing this:

Money.parse!("0E+1", :USD) # %Money{amount: 100, currency: :USD}

So converting to a string before parsing Money is resulting in $1 when the original input was 0, or more specifically 0E+1.

Passing the Decimal directly to Money works just fine.

Decimal.new("0E+1") |> Money.parse!(:USD) # %Money{amount: 0, currency: :USD}

I'm not sure if this should be "fixed" -- is Money supposed to be able to parse scientific notation? Maybe it just needs to be called out as not supported?