DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Fred has posted 10 posts at DZone. View Full User Profile

Determine If A Syntactically Correct Series Of Characters Is Numeric (in A Way Cool Way) In Ruby

08.07.2010
| 623 views |
  • submit to reddit
        While foo.to_f never throws an error (it returns 0 instead), but Float(foo) does.
def is_numeric?(n) Float n rescue false end
http://www.ruby-forum.com/topic/88507#168925

Re: ruby equivalent PHP function is_numeric?
Posted by unknown (Guest) on 17.11.2006 19:14  
On Sat, 18 Nov 2006, Josselin wrote:

>
> joss


   harp:~ > cat a.rb
   def is_numeric?(n) Float n rescue false end

   args =
     1.2345,
     12345678987654321,
     0,
     0.0,
     ".001",
     123435.12345,
     "123435.",
     "1.50130937545297e+68",
     "a",
     "a42",
     "42a",
     1_2_3.42,
     "1_2_3.42",
     "_1_2_3_.42_",
     "__1__2_3_.42__"

   args.each{|a| puts "is_numeric?(#{ a.inspect }) #=> #{ is_numeric? a 
}"}



   harp:~ > ruby a.rb
   is_numeric?(1.2345) #=> 1.2345
   is_numeric?(12345678987654321) #=> 1.23456789876543e+16
   is_numeric?(0) #=> 0.0
   is_numeric?(0.0) #=> 0.0
   is_numeric?(".001") #=> 0.001
   is_numeric?(123435.12345) #=> 123435.12345
   is_numeric?("123435.") #=> 123435.0
   is_numeric?("1.50130937545297e+68") #=> 1.50130937545297e+68
   is_numeric?("a") #=> false
   is_numeric?("a42") #=> false
   is_numeric?("42a") #=> false
   is_numeric?(123.42) #=> 123.42
   is_numeric?("1_2_3.42") #=> 123.42
   is_numeric?("_1_2_3_.42_") #=> false
   is_numeric?("__1__2_3_.42__") #=> false



-a