Hello,
While coding tests for a hobby project of mine, I stumbled upon something odd when directly comparing Decimal
s – which is a bad idea but it’s inevitable when doing assert
equal in tests with maps that contain Decimal
s.
iex> {:ok, d1} = Decimal.parse("00020.400")
{:ok, #Decimal<20.400>}
iex> {:ok, d2} = Decimal.parse("00020.4")
{:ok, #Decimal<20.4>}
iex> Decimal.cmp(d1, d2)
:eq
iex> > d1 == d2
false
The last part made my tests fail. What further surprised me is that there is a way to equalize Decimal
s that have to parse such zero-padded data: Decimal.reduce.
iex> {:ok, d1} = Decimal.parse("00020.400"); d1 = Decimal.reduce(d1)
{:ok, #Decimal<20.4>}
iex> {:ok, d1} = Decimal.parse("00020.4"); d2 = Decimal.reduce(d2)
{:ok, #Decimal<20.4>}
iex> d1 == d2
true
Now the tests succeed.
Maybe this will help you one day.
(Alternatively, you could just do String.trim(your_string, "0")
before parsing, which will rid you of all zeroes both in front and at the back.)