This is my code:
print('What amount would you like to calculate tax for? ')
subtotal = gets.chomp
taxrate = 0.078
tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so the grand total is $#{subtotal + tax}."
First output: What amount would you like to calculate tax for?
Input: 100.
Final output: Tax on $100 is $, so the grand total is $100.
I believe I should be getting a tax rate of $7.79999999 and a grand total of 107.7999999. I’d like to make the code a little better by doing things like stripping the $ from the input, should a user mistakenly enter a $, and rounding up to the nearest cent. First, I need to understand why I’m not getting any output or addition, though, right?
Let us go through your code:
gets.chompgives you a String so this:is using
String#*rather than multiplying numbers:But
taxrate.to_iwill give you zero andany_string * 0gives you an empty String. So you’re getting exactly what you’re asking for, you’re simply asking for the wrong thing.You need to convert
subtotalto a number withto_iorto_f:You won’t need the
chompif you useto_iorto_f, those methods will ignore the trailing whitespace on their own.That should give you a sensible value in
tax.