I need to produce a String that will be later printed and cannot have a decimal point in it. For that I am trying to use the io_lib:format module in Erlang, but I am uncertain of what is the appropriate format to achieve this.
For example, I can use the following up to the .1 precision, but not .0
io_lib:format("~.2f", [789.1234]).
789.12
io_lib:format("~.1f", [789.1234]).
789.1
io_lib:format("~.0f", [789.1234]).
** exception error: bad argument
in function io_lib:format/2
called as io_lib:format("~.0f",[789.1234])
All I need is from:
789.1234 produce the string "789"
123.0 produce the string "123"
I know I can do a "re" replacement but I am trying to find a format-elegant way.
If doing math with floats, you need to add a decimal point, otherwise it will be treated as an int. See the Floating point constants page for details. The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point.
The number of "supported" digits is, however, much larger, for example float will usually support up to 38 decimal digits and double will support up to 308 decimal digits, but most of these digits are not significant (that is, "unknown").
If you truncate a float number in erlang it will become integer. Below is code.
1> is_float(round(1.5)).
false
2> is_integer(round(1.5)).
true
3> is_float(trunc(1.5)).
false
4> is_integer(trunc(1.5)).
true
5> round(1.5).
2
6> trunc(1.5).
1
1> float_to_list(-223.56,[{decimals,0}]).
"-224"
2> float_to_list(223.56,[{decimals,0}]).
"224"
3> float_to_list(223.44456,[{decimals,0}]).
"223"
4> float_to_list(223.44456,[{decimals,6}]).
"223.444560"
5> float_to_list(223.44456,[{decimals,6},compact]).
"223.44456"
erlang:float_to_list/2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With