Harish Harish - 1 year ago 70
Ruby Question

How to convert a String to Integer or Float

I have a text field where the user can enter a number, and I want to be able to convert the string to an 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 Source

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?(',')

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download