Menu
Coddy logo textTech

Formatted Output (sprintf)

Part of the Fundamentals section of Coddy's R journey — lesson 37 of 78.

challenge icon

Challenge

Easy

In the previous lesson, you completed the Bill Split Calculator with all calculations. Now, improve the output formatting using sprintf() to display monetary values with exactly 2 decimal places.

Modify the output lines that display dollar amounts to use sprintf() for formatting. The sprintf() function 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 sprintf() to format each monetary value. For example, sprintf("%.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.

Try it yourself

# TODO: Write your code below
# Use cat() to display the welcome message
# Remember to use \n for new lines
cat("Welcome to the Bill Split Calculator!\nLet's split your bill fairly.\n")

# Read user inputs
con <- file("stdin", "r")
bill <- as.numeric(suppressWarnings(readLines(con, n = 1)))
tip_percent <- as.numeric(suppressWarnings(readLines(con, n = 1)))
people <- as.numeric(suppressWarnings(readLines(con, n = 1)))
close(con)

# Display confirmation message
cat("Bill: $", bill, "\n", sep = "")
cat("Tip: ", tip_percent, "%\n", sep = "")
cat("People: ", people, "\n", sep = "")

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

# Display calculation results
cat("Tip amount: $", tip_amount, "\n", sep = "")
cat("Total with tip: $", total, "\n", sep = "")

# Calculate per person amount
per_person <- total / people

# Display per person amount
cat("Each person pays: $", per_person, "\n", sep = "")

All lessons in Fundamentals