13

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.

4

3 回答 3

25

如果您在 erlang 中截断浮点数,它将变为整数。下面是代码。

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
于 2013-05-17T07:10:45.993 回答
18
1> float_to_list(223.44456,[{decimals,0}]).
"224"

2> float_to_list(223.44456,[{decimals,6}]).        
"223.444560"

3> float_to_list(223.44456,[{decimals,6},compact]).       
"223.44456"

erlang:float_to_list/2

于 2013-05-16T23:52:27.053 回答
0

要转换为整数,您可以执行以下操作:

erlang:list_to_integer(erlang:float_to_list(789.1234,[{decimals,0}])).

如果你想保持原样,那么

erlang:float_to_list(789.1234,[{decimals,0}]).
于 2017-04-24T10:57:12.193 回答