How to convert a string to Integer or Float

I have a text box in which the user can enter a number, and I want him to be able to convert the string to an integer or put based on user input. Is there an easy way to do this in Ruby?

For instance:

User Input: "123" -> Output: 123 User Input: "123.99" -> Output: 123.99 
+3
source share
7 answers

You can do it as follows:

 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 results based on input. If you delete this empty line, instead of an error there will be 0.

-6
source

Use to_i or to_f in a string

 irb(main):001:0> "13".to_i => 13 irb(main):002:0> "13".to_f => 13.0 
+4
source

This is a common exercise. There may be more elegant ways to do this, but this is the easiest airliner I've come with.

 def to_number(value) return if value.blank? (value.to_f % 1) > 0 ? value.to_f : value.to_i end 

Keep in mind that the operator’s mod is not entirely accurate. But for this case, it should work for any string number.

+1
source

If you just want to not show decimal numbers when the input looks like an integer, you can convert your input to Float and use '%g' to display the number.

You can get unexpected behavior or write some logic to check if your numeric Float or Integer object is different.

 def display_number(input) '%g' % Float(input) end puts display_number("1") puts display_number(2) puts display_number("1.23") puts display_number(2.3456) puts display_number(Math::PI) puts display_number("not a number") # => 1 # 2 # 1.23 # 2.3456 # 3.14159 # convert_to_int_or_float.rb:2:in `Float': invalid value for Float(): "not a number" (ArgumentError) 
0
source

This will extend String with two new methods, but you just need to call #to_numeric for any string, and it will return a float or int, respectively.

 class String def numeric_string? Float(self) != nil rescue false end def to_numeric if self.numeric_string? if self.index('.') return self.to_f else return self.to_i end end end end ['2.0', '15', '4500.1234', '111.234'].each do |str| puts str.to_numeric end # 2.0 # 15 # 4500.1234 # 111.234 

Hope this helps!

0
source

You can use the to_f function with round to change the string to float with exact decimal to_f . For example, I am printing text about the frequency value in a .pdf file. Raw data in string .

 text "#{(@qsos.frequency.to_f).round(3)} MHz" 

As a result, original text such as 7.13500 will be converted to 7.135 . If we try to round value directly, it will return an error, as in string . So, we need to first convert it to a floating point number before we define the decimal places.

0
source

I would use:

 def convert(input) [:Integer, :Float].each do |m| begin return Kernel.method(m).call(input) rescue ArgumentError end end nil end convert('') # => nil convert(' ') # => nil convert('1') # => 1 convert('1.0') # => 1.0 convert('.01') # => 0.01 

How it works?

Integer() and Float() are Kernel class methods, therefore

 Kernel.method(m) 

returns a method object, allowing call to send it an input value. If it succeeds in returning the return value and each loop ends. If it explodes the rescue ArgumentError trap, and each loop continues. If the loop ends without shorting to return , then nil returns Ruby.

-one
source

Source: https://habr.com/ru/post/1012535/


All Articles