Truncate a float in Erlang
Solution 1
Are you looking for something like this:
6> F = 5/2.
2.50000
7> io_lib:format("~.1f",[F]).
["2.5"]
8> io_lib:format("~.2f",[F]).
["2.50"]
9> io_lib:format("~.3f",[F]).
["2.500"]
If yes, have a look at the io_lib module.
Solution 2
mochinum:digits
converts a float to a string with an appropriate level of precision.
1> mochinum:digits(1.1).
"1.1"
2> mochinum:digits(1.2345).
"1.2345"
Not exactly what the OP requested, but useful nonetheless.
Solution 3
Alternatively you could use the function you were already using.
float_to_list(0.02,[{decimals, 2}])
outputs '0.02'
Or for Elixir users ;)
:erlang.float_to_list(5.231,[{:decimals, 2}])
outputs '5.2'
Solution 4
This link provides functions that truncate/floor or ceil or round a float. Given those you can round to 2 digits by multiplying by 100, rounging and then dividing back by 100 (and possibly rounding again to avoid precision errors)
Related videos on Youtube
Comments
-
BAR almost 3 years
I am using a function to create a list from a float.
float_to_list(0.02).
It returns:
"2.00000000000000000000e-002"
I need it to give me a number exactly like:
"0.20"
If I fed it 5.23
"5.23"
If I fed it 5.5
"5.50"
So basically the number rounded to two decimal places. Probably an easy fix.
Thanks
EDIT:
I would like to use the io format it looks like it might work,
but it dosen't in this example:
wxTextCtrl:setValue( TcGrossProfit, io:format("~p", [NUMBER]), ),
seems textctrl wants a string, I don't want to print it to the screen.
-
ndim over 13 years+1 for being the only answer mentioning
io_lib
- the thing that formats to strings (aka lists), instead of just printing the output likeio
. -
ndim over 13 years@pst Still, the only answer mentioning
io_lib
, as of now.