[ACCEPTED]-Truncate a float in Erlang-floating-point
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 1 yes, have a look at the io_lib module.
Alternatively you could use the function 2 you were already using.
float_to_list(0.02,[{decimals, 2}])
outputs '0.02'
Or 1 for Elixir users ;)
:erlang.float_to_list(5.231,[{:decimals, 2}])
outputs '5.2'
mochinum:digits
converts a float to a string with an appropriate 2 level of precision.
1> mochinum:digits(1.1).
"1.1"
2> mochinum:digits(1.2345).
"1.2345"
Not exactly what the 1 OP requested, but useful nonetheless.
This link provides functions that truncate/floor 5 or ceil or round a float. Given those you 4 can round to 2 digits by multiplying by 3 100, rounging and then dividing back by 2 100 (and possibly rounding again to avoid 1 precision errors)
I know people don't like the, "I am 6 not an expert in language X" answers, but 5 the printf command is quite ubiquitous so 4 I will say, look for an analog of printf 3 in Erlang.
Edit: It looks like the format 2 and fwrite may be those analogs. For more 1 info from erlang.org.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.