MIT license

Copyright (c) 2008, Doug Edmunds

Strings to Numbers

Is it a float or an integer?

What if your Erlang function requires a number (an integer or a float) as a parameter?  How can you convert the string representation to the correct data type?  For example, in the e2d_vec.erl file (see Making Modifications), there is this function:

len({X,Y,Z}) when is_float(X), is_float(Y), is_float(Z) ->


If you know the datatype you can include it in the erlbol clause for that function by using list_to_float/1 or list_to_integer/1.  See the example of the cross function under Connect to e3d_vec.

But sometimes you don't have a particular type, you just need a numeric value.  Erlang doesn't come with a function that will convert any number-as-string.  It requires that the string "look like" a  float or "look like" an integer.  list_to_float("3") does not work.  It has to be  list_to_float("3.0").  Once you have numbers, you can do math with them.  You can add/subtract/multiply/divide any mix of integers and floats.   X = 23 + (44.32 / 22).  is perfectly valid.  It binds X to 25.014545454545456. 

Using X = 23 + (44.32 / 22) as a model,  I might have this generic function, where A, B, and C can be any mix of integers and floats. 

add_to_division(A, B, C) ->  
    A + (B / C).

Instead of coding all the possible combinations, use this utility function (which is in erlbol.erl):

list_to_number(Number) ->
try list_to_integer( Number) of
Val_integer -> Val_integer
error:_Why -> try list_to_float(Number) of
Val_float -> Val_float
error: Reason -> Reason

The erlbol case statement for add_to_division will look something like this:

case Function of ...

     add_to_division -> 
[A , B ,C| _D] = Tail,
try ?MODULE:Function(list_to_number(A), list_to_number(B), list_to_number(C)) of
Val -> Val
error:Reason -> Reason
end ;

list_to_number/1 will convert its parameter to either a float or an integer (or catch the error) as appropriate, before it is sends it to add_to_division/3.


Content © 2007 Erlbol |
Powered by Etomite CMS.