5

I need to do some calculations but I'm getting a problem with values which are very low, for example, I need to get the 2.7% of 0.005 and I end up with 1.3500000000000003e-4 which is not what I'm looking for, I just need to know how can I get an accurate percetage of those values, what I'm doing right now is <value> * 2.7 / 100 which works great for integers or floats greater than 0.05.

For example, the one that I need which is 2.7% of 0.005 needs to be shown as 0.000135.

Peer Stritzinger
  • 8,232
  • 2
  • 30
  • 43
Aguxez
  • 378
  • 5
  • 16

1 Answers1

15

First, understand that the language isn't broken, it's just that computers are just really bad at doing floating point math.

So, in a sense 1.3500000000000003e-4 is accurate, but your issue here is that Elixir prints the (very small and very large) floats in exponent notation. There are a few ways you can print it as 0.000135:

  • Use Erlang's float_to_binary:

    :erlang.float_to_binary(0.005 * 2.7 / 100, [:compact, {:decimals, 10}])
    #=> "0.000135"
    
  • Use :io.format:

    :io.format("~f~n",[0.005 * 2.7 / 100])
    #=> "0.000135"
    
  • Or use exprintf which is a nice Elixir wrapper around Erlang's :io module


Notice the result is a string and not a number in the above examples - since you're just formatting / printing it in decimal.

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
  • Great, I must've mentioned but i'm storing these values in a database, should I have used `:string` instead of `:float`? :-/ – Aguxez Jul 07 '17 at 01:18
  • 1
    No, store them as is. The values are accurate, it's just how Elixir represents them. – Sheharyar Jul 07 '17 at 01:21
  • Oh ok, I understand and fixed it now, it was kinda driving me crazy, the values are floats in the database but I'm just formatting them on the Phoenix templates and everything else, thanks! – Aguxez Jul 07 '17 at 01:43
  • 2
    Should have mentioned this before: If the numbers you are storing in the DB are sensitive or require very high precision (money for example), use [`Decimal`](https://stackoverflow.com/q/224462/1533054) not `Float`. – Sheharyar Nov 08 '18 at 21:57