[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

validity test for Float

Craig

5/28/2006 2:52:00 PM

Q from a newbie:

Is there any way to test if a string is valid to pass to Float?

irb(main):025:0> Float( "2.0" )
=> 2.0
irb(main):026:0> Float( "mambo" )
ArgumentError: invalid value for Float(): "mambo"
from (irb):26:in `Float'
from (irb):26
irb(main):027:0> "2.0".to_f
=> 2.0
irb(main):028:0> "mambo".to_f
=> 0.0

to_f doesn't seem to do it, as it returns 0.0 even if the string is
invalid.

Many TIA,
Craig

4 Answers

Tim Hunter

5/28/2006 3:44:00 PM

0

Craig wrote:
> Q from a newbie:
>
> Is there any way to test if a string is valid to pass to Float?
>
> irb(main):025:0> Float( "2.0" )
> => 2.0
> irb(main):026:0> Float( "mambo" )
> ArgumentError: invalid value for Float(): "mambo"
> from (irb):26:in `Float'
> from (irb):26
> irb(main):027:0> "2.0".to_f
> => 2.0
> irb(main):028:0> "mambo".to_f
> => 0.0
>
> to_f doesn't seem to do it, as it returns 0.0 even if the string is
> invalid.
>
> Many TIA,
> Craig
>
begin
Float("mambo")
rescue ArgumentError, TypeError
puts "illegal argument to Float"
end

samuel.murphy

5/28/2006 5:04:00 PM

0

You could consider converting to a appropriate base:

>> a = "mambo".to_i(base=23).to_f
=> 273481.0

(not sure why a lower base didn't work)

Oh, and for the too literal -> :-) :-)

Craig

5/28/2006 8:34:00 PM

0

Thanks super! It works, but feels somewhat kludgy. It would be nice
to have some sort of String#isnum? as a built-in.
Craig

Tim Hunter

5/28/2006 9:56:00 PM

0

Craig wrote:
> Thanks super! It works, but feels somewhat kludgy. It would be nice
> to have some sort of String#isnum? as a built-in.
> Craig
>

So, code it up yourself:

class String
def isnum?(s)
is = true
begin
Float(s)
rescue ArgumentError, TypeError
is = false
end
return is
end
end

Put that in a file called "mystuff.rb" and save mystuff.rb in one of the
directories Ruby looks for required files. Then at the top of every
program you want to use it, add

require 'mystuff'

Voila!