Elixir: Integers, Floats, Operators and Arithmetic
Integers and Floats are types of number that are used in Elixir. Integers are whole numbers, whereas Floats are floating point numbers, they have a decimal point value. For instance, 5
is an Integer, 5.0
is a Float. In order to check, Elixir provides is_integer()
and is_float()
methods. They are used like so:
Integer and Float Methods
Some more Integer and Float methods, and how they behave:
Parsing
The parse method ( .parse()
) runs the argument against the preceding module and returns the argument as an instance of that module (if it can find one, otherwise it presents an :error
), followed by the ‘leftovers’. For instance if an Integer is parsed with an argument of "45Z"
, the 45
is converted into an integer and the "Z"
is returned, remaining a string.
The return would look like {45, "Z"}
, a tuple. Here are some more examples of how Integers and Floats act when parsed:
== and ===
==
is used for equivalence, as we have seen before. 5
and 5.0
are the same amount, and so 5 == 5.0 == true
. However 5
and 5.0
are not the same thing, as one is an integer and one is a float, and so there is ===
, the case operator. With the case operator 5 === 5.0 == false
.
Basic Arithmetic
Elixir provides operators for basic arithmetic. It is easy as 1 + 2 == 3
. Here are the basic operators for this:
arithmetic operator | means: |
+ | adds |
- | subtracts |
* | multiplies |
/ | divides, always returns a float |
div | divides, returns a whole number without any remainder |
rem | remainder, this returns a value that is the remainder when one number is divided by another |
When using div
and rem
the syntax is different to using the other operators. Creating an expression with these operators looks like so:
Comparison Operator | Means: |
== | Is equal to |
!= | Is not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Here we can see that the !
acts as a negating character, and basically says ‘is not’ to the operator that it sits with. For instance !>
would be the same as putting <
. The comparison operators can also be used to compare data types. For instance: