Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an Elixir number in exponent notation to integer

Tags:

elixir

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.

like image 371
Lin Reid Avatar asked Oct 22 '15 20:10

Lin Reid


1 Answers

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 – round
  • Kernel.trunc/1 – drop digits after decimal point
  • Float.round/2 – round with precision
  • Float.floor/2 – round up with precision
  • Float.ceil/2 – round down with precision

The 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
like image 135
Patrick Oscity Avatar answered Sep 28 '22 10:09

Patrick Oscity