dimitarvp
Decimal comparison oddity: sharing how I solved it
Hello,
While coding tests for a hobby project of mine, I stumbled upon something odd when directly comparing Decimals – which is a bad idea but it’s inevitable when doing assert equal in tests with maps that contain Decimals.
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 Decimals 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.)
Most Liked
LostKobrakai
==/2 does structural compasions and not logical. Therefore you shouldn‘t use it for structs, where different values in the structs‘ fields are still considered the same value, which is true for decimals (different number ot trailing 0‘s) but also for some core structs like datetimes. Use functions of those structs to compare them instead of the equals operator.
Popular in Other Resources
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








