If you want Ruby to raise an exception for invalid (i.e. non-decimal) input, you can also use:
numb = Float(gets)
Some examples:1
gets | gets.to_f | Float(gets)
--------+------------+--------------
'1' | 1.0 | 1.0
'.5' | 0.5 | 0.5
'1.2.3' | 1.2 | ArgumentError
'' | 0.0 | ArgumentError
'foo' | 0.0 | ArgumentError
Because of the exception, you probably want to wrap it in a begin-rescue block, something like:
puts 'Amount with decimals:'
begin
numb = Float(gets)
rescue ArgumentError
puts 'Invalid amount'
retry
end
1 note that gets includes the newline character "\n" if the input is entered with return. I've omitted it because trailing newlines are ignored by both, to_f and Float().
mult.to_f?STDOUT.flushcan usually be omitted. Ruby auto-flushes when writing to a terminal device (tty).