How do I use the modulo operator in Elixir?
For example in Ruby you can do:
5 % 2 == 0
How does it differ from Ruby's modulo operator?
The modulo operation (abbreviated “mod”, or “%” in many programming languages) is the remainder when dividing. For example, “5 mod 3 = 2” which means 2 is the remainder when you divide 5 by 3.
In Elixir, division using the division operator (/) always results in a float no matter whether the operands are integers or floats. So 5 / 2 is 2.5 and 8 / 2 is 4.0. Javascript behaves similarly, but Javascript has a single numerical data type.
The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.
If both operands for %, the modulus operator have type int, then exprleft % exprright evaluates to the integer remainder. For example, 8 % 3 evaluates to 2 because 8 divided by 3 has a remainder of 2. When both operands have type int, the modulus operator (with both operands) evaluates to int.
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 thedividend
.Raises an
ArithmeticError
exception if one of the arguments is not an integer, or when thedivisor
is 0.
The main differences compared to Ruby seem to be:
rem
only works with integers, but %
changes its behavior completely depending on the datatype.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With