Modulo operator in Elixir

Use rem/2 see: https://hexdocs.pm/elixir/Kernel.html#rem/2 So in Elixir your example becomes:

rem(5,2) == 0

which returns false

BTW what you wrote using % in Elixir simply starts a comment to the end of the line.


Use Integer.mod/2, see: https://hexdocs.pm/elixir/Integer.html#mod/2

iex>Integer.mod(-5, 2)
1

For integers, use Kernel.rem/2:

iex(1)> rem(5, 2)
1
iex(2)> rem(5, 2) == 0
false

From the docs:

Computes the remainder of an integer division.

rem/2 uses truncated division, which means that the result will always have the sign of the dividend.

Raises an ArithmeticError exception if one of the arguments is not an integer, or when the divisor is 0.

The main differences compared to Ruby seem to be:

  1. rem only works with integers, but % changes its behavior completely depending on the datatype.
  2. The sign is negative for negative dividends in Elixir (the same as Ruby's remainder):

Ruby:

irb(main):001:0> -5 / 2
=> -3
irb(main):002:0> -5 % 2
=> 1
irb(main):003:0> -5.remainder(2)
=> -1

Elixir:

iex(1)> -5 / 2
-2.5
iex(2)> rem(-5, 2)
-1

Elixir's rem just uses Erlang's rem, so this related Erlang question may also be useful.

Tags:

Modulo

Elixir