Menu
Coddy logo textTech

Formatted Output

Part of the Fundamentals section of Coddy's Ruby journey — lesson 38 of 88.

challenge icon

Challenge

Easy

In the previous lesson, you completed the Bill Split Calculator with all calculations. Now, improve the output formatting using Ruby's string formatting to display monetary values with exactly 2 decimal places.

Modify the output lines that display dollar amounts to use format strings with the % operator. Ruby allows you to format numbers with a specific number of decimal places using %.2f for 2 decimal places.

Update the following output lines to show exactly 2 decimal places for all monetary values:

  • Bill: $[bill]
  • Tip amount: $[tip_amount]
  • Total with tip: $[total]
  • Each person pays: $[per_person]

Use the % operator to format each monetary value. For example, "%.2f" % value formats a number to 2 decimal places.

For example, if the inputs are 85.50, 18, and 3, the complete output should be:

Welcome to the Bill Split Calculator!
Let's split your bill fairly.
Bill: $85.50
Tip: 18%
People: 3
Tip amount: $15.39
Total with tip: $100.89
Each person pays: $33.63

Note: The tip percentage and number of people should remain as whole numbers without decimal formatting (use %g to avoid trailing zeros).

Try it yourself

# TODO: Write your code below
# Use puts to display the welcome message
puts "Welcome to the Bill Split Calculator!\nLet's split your bill fairly."

# Read user inputs
bill = gets.chomp.to_f
tip_percent = gets.chomp.to_f
people = gets.chomp.to_f

# Display confirmation message
puts "Bill: $%g" % bill
puts "Tip: %g%%" % tip_percent
puts "People: %g" % people

# Calculate tip amount and total
tip_amount = bill * tip_percent / 100
total = bill + tip_amount

# Display calculation results
puts "Tip amount: $%g" % tip_amount
puts "Total with tip: $%g" % total

# Calculate per person amount
per_person = total / people

# Display per person amount
puts "Each person pays: $%g" % per_person

All lessons in Fundamentals