How do I convert an Elixir exponent to an integer?
I'd like to convert something like 1.0e2
to 100
.
I've googled around for a solution but haven't been able to find one.
What you call exponent is really just a floating point number written in scientific notation, sometimes also called exponential notation. The actual exponent is actually just a part of this whole thing. Together with the mantissa it allows us to conveniently represent very large and/or small numbers:
mantissa * (10 ^ exponent)
So in Elixir, as in many other languages, the number 1.23 * (10 ^ 5)
can be written as 1.23e5
. If you type your example number 1.0e2
into iex
, you will see that it is really just a convenience on top of floating point numbers:
iex> 1.0e2
100.0
So the question should really be: "How do I convert a float to an integer?". The answer to this is that you can use one of the following functions to achieve this:
Kernel.round/1
– roundKernel.trunc/1
– drop digits after decimal pointFloat.round/2
– round with precisionFloat.floor/2
– round up with precisionFloat.ceil/2
– round down with precisionThe Kernel
functions are allowed in guard tests, and you don't need to put the Kernel.
in front in order to call them. The Float
functions additionally allow you to specify a precision in order to preserve some digits after the decimal point. With your example it doesn't really matter which one you use, because 100.0
is a whole number. The behavior of the functions mentioned above is however best illustrated with a different number, say 1.55
:
iex> round(1.55)
2
iex> trunc(1.55)
1
iex> Float.round(1.55)
2.0
iex> Float.round(1.55, 1)
1.6
iex> Float.floor(1.55)
1.0
iex> Float.floor(1.55, 1)
1.5
iex> Float.ceil(1.55)
2.0
iex> Float.ceil(1.55, 1)
1.6
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