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
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With