Colton Haugrud - 1 year ago 52
Ruby Question

# How to return a number using to_i when the input starts with "\$"

`to_i`
returns 0 whenever the input starts by anything other than an integer. For example, if I input
`\$32`
it returns 0, but if I enter
`32`
, it returns the number 32. I found another post that said
`to_i`
only accepts digits, but did not offer an alternative solution.

Is there a way around this? I want the user to be able to input a "\$" before their number. As it stands, my code looks like this:

``````puts"What is the cost of a gallon of paint?"

cost=gets.chomp.to_i

total_cost=cost*@gallons_needed"
``````

Meditate on these:

``````"\$1\n"[1..-1].to_i # => 1
"\$1.99\n"[1..-1].to_i # => 1
"\$100.99\n"[1..-1].to_i # => 100
``````

This breaks down when there's a leading `-`:

``````"-\$100.99\n"[1..-1].to_i # => 0
``````

That can be fixed using `sub` instead of a slice:

``````"-\$100.99\n".sub('\$', '').to_i # => -100
``````

The problem is, money is not all integers, so `to_i` is probably not really what you want. Instead you should be using `to_f`:

``````"\$1\n".sub('\$', '').to_f # => 1.0
"\$1.99\n".sub('\$', '').to_f # => 1.99
"\$100.99\n".sub('\$', '').to_f # => 100.99
"-\$100.99\n".sub('\$', '').to_f # => -100.99
"\$-100.99\n".sub('\$', '').to_f # => -100.99
``````

Note: It isn't necessary to use `chomp` to remove the trailing new-line. `to_i` and `to_f` will stop when they see a non-digit:

``````"1\n".to_i # => 1
"1.99\n".to_f # => 1.99

"1 1\n".to_i # => 1
"1.99 2\n".to_f # => 1.99
``````

Again, because of this behavior, `"\n"` and `1\n` or `2\n` will be ignored.

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