Skip to content

Instantly share code, notes, and snippets.

@faizaanshamsi
Last active December 28, 2015 08:19
Show Gist options
  • Save faizaanshamsi/7470743 to your computer and use it in GitHub Desktop.
Save faizaanshamsi/7470743 to your computer and use it in GitHub Desktop.
Takes a currency input and amount tendered, validates input, returns amount of change due.
puts "What is the amount due?"
amount_due = gets.chomp
if (amount_due[/^[1-9]\d*(\.\d+)?$/] == false) || (amount_due.scan(/\./).length > 1)
puts "Warning: Invalid currency detected! Exiting..."
abort
end
puts "What is the amount tendered?"
amount_tendered = gets.chomp
if (amount_tendered[/^[1-9]\d*(\.\d+)?$/] == false) || (amount_tendered.scan(/\./).length > 1)
puts "Warning: Invalid currency detected! Exiting..."
abort
end
amount_tendered = amount_tendered.to_f
amount_due = amount_due.to_f
if amount_tendered < amount_due
puts "WARNING: Customer still owes $#{sprintf('%.2f', (amount_due - amount_tendered))}! Exiting..."
abort
end
puts "===Thank You!===", "The total change due is $#{sprintf('%.2f', (amount_tendered - amount_due))}",
"", Time.now.strftime("%m/%d/%Y %I:%M%p" ) , "================"
#How to improve:
#Shorten Conditions
#sprintf vs. printf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment