Reputation: 36802
Given a string from user input, I want to convert it to a Fixnum
or Integer
if the string is a valid int. I do not want to convert to an int if the string is a float. If that fails, I then want to try to convert the string to a Float
. If the string is not either of these I intend to just raise an exception.
It seems that String#to_i
just truncates any Float
value rather than providing any sort of error. I know I could do some regexing to determine whether a String
is a valid int, but it seems like there should be some built-in conversion that fails if a String
has anything other than digits. Am I missing something?
For example. I want something like this that fails instead of returning 1
irb(main):092:0> "1.4".to_i
=> 1
irb(main):093:0> "1.4e5".to_i
=> 1
Upvotes: 0
Views: 3186
Reputation: 41
My solution
def typing(value)
if value.to_i.to_s == value
value.to_i
elsif value.to_f.to_s == value
value.to_f
else
value
end
end
Upvotes: 2
Reputation: 24815
I don't like rescue so this is my version :)
def to_fi(str)
if str.to_i == str.to_f
str.to_i
else
str.to_f
end
end
a = "1"
to_fi a
#=> 1
a = "1.0"
to_fi a
#=> 1
a = "1.2"
to_fi a
#=> 1.2
Upvotes: 0
Reputation: 4088
.to_f or .to_f by definition never raise error and if they can't convert the string return 0. You can use the clases Integer and Float.
this method return the error raised or float number if first can convert to integer
def validate_number(string)
begin
Integer(string)
Float(string)
rescue => e
e
end
end
Upvotes: -1
Reputation: 168101
def int_then_float string
Integer(string)
rescue ArgumentError
Float(string)
end
Upvotes: 7