listerlangfloating-point

Truncate a float in Erlang


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

 float_to_list(0.02).

It returns:

"2.00000000000000000000e-002"

I need it to give me a number exactly like:

"0.20"

If I fed it 5.23

"5.23"

If I fed it 5.5

"5.50"

So basically the number rounded to two decimal places. Probably an easy fix.

Thanks

EDIT:

I would like to use the io format it looks like it might work,

but it dosen't in this example:

wxTextCtrl:setValue( TcGrossProfit, io:format("~p", [NUMBER]), ),

seems textctrl wants a string, I don't want to print it to the screen.


Solution

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