ruby string to float code example

Example 1: ruby string to int

a = "42" # => '42'
a.to_i # => 42

# But if you might not have a number in your String, you should rather 
# use this instead, as to_i doesn't throw an Error:

"42test123".to_i # => 42
Integer("42test123") # => ArgumentError
Integer("42") # => 42

Example 2: converst string to int ruby

Integer('5abc') #=> ArgumentError: invalid value for Integer(): "5abc"
Integer('5') #=> 5

Example 3: convert float to int ruby

Try Float.round.

irb(main):001:0> 5.44.round
=> 5
irb(main):002:0> 5.54.round
=> 6

Tags:

Ruby Example