Truncate a float in Erlang

前端 未结 5 1998
孤独总比滥情好
孤独总比滥情好 2020-12-06 17:35

I am using a function to create a list from a float.

 float_to_list(0.02).

It returns:

\"2.00000000000000000000e-002\"


        
相关标签:
5条回答
  • 2020-12-06 17:44

    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 module io_lib.

    0 讨论(0)
  • 2020-12-06 17:47

    I know people don't like the, "I am not an expert in language X" answers, but the printf command is quite ubiquitous so I will say, look for an analog of printf in Erlang.

    Edit: It looks like the format and fwrite may be those analogs. For more info from erlang.org.

    0 讨论(0)
  • 2020-12-06 17:55

    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)

    0 讨论(0)
  • 2020-12-06 17:58

    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.

    0 讨论(0)
  • 2020-12-06 17:59

    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'

    0 讨论(0)
提交回复
热议问题