Converting numeric string to numeric in Ruby

ruby

Solution

You can use `BigDecimal#frac` to achieve what you want

require 'bigdecimal'

def to_numeric(anything)
  num = BigDecimal.new(anything.to_s)
  if num.frac == 0
    num.to_i
  else
    num.to_f
  end
end

It can handle

#floats
to_numeric(2.3) #=> 2.3

#rationals
to_numeric(0.2E-4) #=> 2.0e-05

#integers
to_numeric(1) #=> 1

#big decimals
to_numeric(BigDecimal.new("2"))

And floats, rationals and integers in form of strings, too

Problem

I want a method like to_numeric(str) which convert numeric string 'str' into its numeric form else return nil. By numeric form if string is in integer method should return integer and it string is in float it should return float. I have tried with following code. It works fine but need better solution if possible. ``` def to_numeric(str) Integer(str) rescue Float(str) if Float(str) rescue nil end ``` One important thing I forgot to mention is "I don't know the type of my input". My use case: ``` arr = [1, 1.5, 2, 2.5, 4] some_input = get_input_from_some_source if arr.include?(to_numeric(some_input)) # do something end ```

Original source