Harish Harish - 12 days ago 9
Ruby Question

Ruby String to Integer or Float

I have a text field where user can enter a number, and I want to be able to convert the string to integer or float based on the user input. Is there an easy way to do that in Ruby?

For example:

User Input: "123" -> Output: 123
User Input: "123.99" -> Output: 123.99

Answer

You could do it like this:

def to_float_or_int(string)
  throw "error" unless string && string.length > 0
  return string.to_f if string.include?('.') || string.include?(',')
  string.to_i
end

The first line ensures that you always get a result based on the input. If you remove that an empty string will yield 0 instead of an error.

Comments