问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/44960798/get-rid-of-scientific-notation