[erlang-questions] fread() for numbers - beginner question

Zvi exta7@REDACTED
Mon Apr 20 22:00:59 CEST 2009


if you don't want to use catch, then you may try read it as a string and
parse yourself later:

1> io_lib:fread("~s", "1").
{ok,["1"],[]}
2> io_lib:fread("~s", "1.0").
{ok,["1.0"],[]}
3> 

i.e.

str2float(Str) ->
     FloatStr = case lists:member($. ,Str) of
                       true -> S;
                       false -> S++".0"
                   end,
    {ok,[Float],_} = io_lib:fread("~f", FloatStr),
    Float.


Zvi



BranchingFactor wrote:
> 
> Thanks for the quick reply,   Robbi.    I was hoping to avoid the
> try-and-try-again approach b/c it doesn't extend so nicely to scanning
> multiple items from a string.  Does Erlang provide any way to read what
> many other programming languages consider to be the printed representation
> of a number?
> 
> --- On Mon, 4/20/09, Robert Raschke <rtrlists@REDACTED> wrote:
> From: Robert Raschke <rtrlists@REDACTED>
> Subject: Re: [erlang-questions] fread() for numbers - beginner question
> To: branchingfactor@REDACTED
> Cc: erlang-questions@REDACTED
> Date: Monday, April 20, 2009, 6:57 AM
> 
> On Mon, Apr 20, 2009 at 10:43 AM, BranchingFactor
> <branchingfactor@REDACTED> wrote:
>> I'd like to io_lib:fread() a number from a string.  Unfortunately, if
> I use
>> "~f" for floating point number, then fread rejects numbers that
> don't have
>> fractional parts:
>>
>>> io_lib:fread("~f", "1").
>> {error,{fread,float}}
>>> io_lib:fread("~f", "1.").
>> {error,{fread,float}}
>>
>> (I find this very strange, since both 1 and 1. can be represented in a
>> floating point number.)
>> And if I use "~d" for decimal integers, then fread won't
> read past the
>> decimal point:
>>
>>> io_lib:fread("~d", "1.0").
>> {ok,[1],".0"}
>>
>> What is the easiest way to scan a number from a string in erlang? 
> Ideally
>> it would scan any number in any input format and return an Erlang object
>> that satisfied the is_number() predicate.
> 
> scan_number(S) ->
>     case io_lib:fread("~f", S) of
>         {error, _} -> io_lib:fread("~d", S);
>         Result -> Result
>     end.
> 
> This doesn't handle 16#ffff and friends though. but you can extend it
> according to you needs.
> 
> And "1." is not a valid Erlang number.
> 
> Robby
> 
> 
> 
> 
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
> 

-- 
View this message in context: http://www.nabble.com/fread%28%29-for-numbers---beginner-question-tp23134368p23143824.html
Sent from the Erlang Questions mailing list archive at Nabble.com.




More information about the erlang-questions mailing list