rails convert string to number

.to_f is the right way.

Example:

irb(main):001:0> "-10".to_f
=> -10.0
irb(main):002:0> "-10.33".to_f
=> -10.33

Maybe your string does not include a regular “-” (dash)? Or is there a space between the dash and the first numeral?

Added:

If you know that your input string is a string version of a floating number, eg, “10.2”, then .to_f is the best/simplest way to do the conversion.

If you’re not sure of the string’s content, then using .to_f will give 0 in the case where you don’t have any numbers in the string. It will give various other values depending on your input string too. Eg

irb(main):001:0> "".to_f 
=> 0.0
irb(main):002:0> "hi!".to_f
=> 0.0
irb(main):003:0> "4 you!".to_f
=> 4.0

The above .to_f behavior may be just what you want, it depends on your problem case.

Depending on what you want to do in various error cases, you can use Kernel::Float as Mark Rushakoff suggests, since it raises an error when it is not perfectly happy with converting the input string.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)