Search code examples
erlang

How to format an erlang float into an integer (without decimal point)


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.


Solution

  • 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