Converting numeric string to numeric in Ruby

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


Convert it to Float using String#to_f method. Since ruby using duck typing you may not care if it can be an Integer.

If it looks like a numeric, swims like a numeric and quacks like a numeric, then it probably is a numeric.

But be aware! to_f does not throw any exceptions:

"foobar".to_f # => 0 

If you really insist to differentiate between Integer and Floats, then you can implement to_numeric like this:

def to_numeric(thing)
  return thing.to_s.to_i if thing.to_s == thing.to_s.to_i.to_s  
  return thing.to_s.to_f if thing.to_s == thing.to_s.to_f.to_s  
  thing
end

It converts an object to an integer, if its string representation looks like an integer (same with float), or returns the unchanged thing if not:

['1', '1.5', 'foo', :bar, '2', '2.5', File].map {|obj| to_numeric obj}
# => [1, 1.5, "foo", :bar, 2, 2.5, File]

Tags:

Ruby