Hel;p with Tip Calculator

H

Hd Pwnz0r

puts "What is the total?"
input = gets.chomp.to_i
puts "What percent do you want to tip?"
input2 = gets.chomp.to_i
percent = 100
tip = input2 * input * 0.01
puts "You should tip $#{tip}"

This is a tip calculator. I want it to work if the person enters $45 or
15%.

Right now, it would only return 0 because they are invalid numbers. It
would only work with an input of 15 or 45. I have really no clue how to
do that.
 
A

Andrei Beliankou

puts "What is the total?"
input = gets.chomp.to_i
puts "What percent do you want to tip?"
input2 = gets.chomp.to_i
percent = 100
tip = input2 * input * 0.01
puts "You should tip $#{tip}"

This is a tip calculator. I want it to work if the person enters $45
or 15%.

Right now, it would only return 0 because they are invalid numbers. It
would only work with an input of 15 or 45. I have really no clue how
to do that.

Use

'45 %'.sub(/%/, '').strip
'14 $'.sub(/[$]/, '').strip

for that.

"strip" can remove unwanted trailing and leading blanks.
"sub" substitutes the charachters in the RE with an empty string
removing them.

Regards,
Andrei
 
H

Hassan Schroeder

Use

'45 %'.sub(/%/, '').strip
'14 $'.sub(/[$]/, '').strip

More universally

input_string.gsub(/\D/, '')

removes any non-[0-9] characters, including white space.
 
H

Hd Pwnz0r

Hassan said:
Use

'45 %'.sub(/%/, '').strip
'14 $'.sub(/[$]/, '').strip

More universally

input_string.gsub(/\D/, '')

removes any non-[0-9] characters, including white space.

I get:

tax.rb:6:in `<main>': undefined method `gsub' for 0:Fixnum
(NoMethodError)

When using that code.

As for Andrei, thanks, that's a good quick fix.
 
H

Hassan Schroeder

tax.rb:6:in `<main>': undefined method `gsub' for 0:Fixnum
(NoMethodError)

When using that code.

Yes, it works on *strings* -- that was the problem you posed. If you
already have a *number*, it's not going to include any symbols like
"$" or "%" in the first place.

--=20
Hassan Schroeder ------------------------ (e-mail address removed)
twitter: @hassan
 
J

jason joo

[Note: parts of this message were removed to make it a legal post.]

or justfor number format permitted
 
J

jason joo

[Note: parts of this message were removed to make it a legal post.]

aha, i forgot positive number and dot. then the regular expression should
be /([\-+]?\d*[.]?\d*)/

eg

if input_string =~ /([\-+]?\d*[.]?\d*)/
input_string = $1
else
#have no number part
input_string = 0
end

9 => "9"
-9 => "-9"
-9.098 => "-9.098"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top