Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure a number is float in Erlang?

Tags:

erlang

io:format throws a badarg exception if the format is ~f but the argument is integer:

io:format("~f", [2]).

Adding 0.0 solves the problem bus there an elegant way?

io:format("~f", [2+0.0]).
like image 805
f3r3nc Avatar asked Feb 28 '11 16:02

f3r3nc


People also ask

How do you know if a number is floating?

Check if the value has a type of number and is not an integer. Check if the value is not NaN . If a value is a number, is not NaN and is not an integer, then it's a float.

What are the two types of number formats supported by Erlang?

In Erlang there are 2 types of numeric literals which are integers and floats.


3 Answers

  • float(Number) convert Number to float
  • list_to_float(String) convert String to float
  • is_float(Term) returns true if Term is a float
like image 176
hdima Avatar answered Nov 05 '22 01:11

hdima


If you don't care about the exact output, you can use:

io:format("~p", [Term]).

This will work with any term, but doesn't give you the same kind of formatting options as ~f would.

like image 37
YOUR ARGUMENT IS VALID Avatar answered Nov 05 '22 01:11

YOUR ARGUMENT IS VALID


Either

io:format("~f", [2.0]).

or

io:format("~f", [float(2)]).

works.

like image 43
Tangui Avatar answered Nov 05 '22 00:11

Tangui