Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to Integer or Float

Tags:

ruby

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
like image 674
Harish Avatar asked Jun 23 '26 23:06

Harish


1 Answers

Use to_i or to_f on the string

irb(main):001:0> "13".to_i
=> 13
irb(main):002:0> "13".to_f
=> 13.0
like image 125
Paul Rubel Avatar answered Jun 25 '26 18:06

Paul Rubel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!