How to escape scientific notation

troubleshooting

#1

Hi all,
I just learned elixir , I want to ask how to escape scientific notation in Math operation

Elixir 1.7.3

iex> 1000 + ( 1000 * 0.11)
1110.0

iex> 1000 + ( 1000 * 0.1)
1.1e3 // I expect 1100.0

iex> 1000 * 0.1
100.0

iex> :erlang.float_to_binary(1000 +(1000 * 0.1), [:compact, { :decimals, 20 }])
“1100.0” // got String type of 1100.0

can somebody explain it ? is this normal behavior ?

I just want to add 10% of original_value with original_value

thx


#2

1100.0 and 1.1e3 are equivalent and equal:

iex(2)> 1.1e3 === 1100.0
true
iex(3)> 1.1e3 == 1100.0
true

So I’m not sure what you are worrying about?

If it is just the representation, then use a function of your choice to format for printing, but keep it as a float as long as you can.


#3

iex> 100 * (1 + 0.1)
110.00000000000001

iex> 100 * (1 + 0.2)
120.0

I’m little confused here


#4

Why? Thats as floats are supposed to work. They often can not represent exact (decimal) numbers.

There are a lot of blog posts and even papers out there in the wild, that will tell you not to use floats for anything but OpenGL.


#5

Ok , I should read document from “h Float” first

There are some very well known problems with floating-point numbers and
arithmetics due to the fact most decimal fractions cannot be represented by a
floating-point binary and most operations are not exact, but operate on
approximations. Those issues are not specific to Elixir, they are a property of
floating point representation itself.

For example, the numbers 0.1 and 0.01 are two of them, what means the result of
squaring 0.1 does not give 0.01 neither the closest representable. Here is what
happens in this case:

• The closest representable number to 0.1 is 0.1000000014
• The closest representable number to 0.01 is 0.0099999997
• Doing 0.1 * 0.1 should return 0.01, but because 0.1 is actually
0.1000000014, the result is 0.010000000000000002, and because this is not
the closest representable number to 0.01, you’ll get the wrong result for
this operation

There are also other known problems like flooring or rounding numbers. See
round/2 and floor/2 for more details about them.

To learn more about floating-point arithmetic visit:

0.30000000000000004.com (http://0.30000000000000004.com/)
• What Every Programmer Should Know About Floating-Point Arithmetic
(http://floating-point-gui.de/)

,
thx @NobbZ


#6

consider using Decimal if lack of precision is an issue… or you need to control it…


#7

Also in case these are amounts of money - don’t use floats :slight_smile: Take a look at the Money implementation in Elixir https://github.com/liuggio/money


#8

thx @outlog , @yurko for the information