Menu
Coddy logo textTech

Formatting with sprintf()

Part of the Logic & Flow section of Coddy's R journey. Lesson 2 of 64.

sprintf() builds a string from a template. Each % placeholder is replaced by the next argument: %s for text, %d for whole numbers and %f for decimals.

name <- "Ada"
age <- 36
print(sprintf("%s is %d years old", name, age))

Output:

[1] "Ada is 36 years old"

%d accepts only whole numbers: sprintf("%d", 2.5) stops with an error.

A precision between % and f sets the number of decimals, so %.2f rounds to two places:

total <- 3 * 4.5 * 1.2
print(sprintf("Total: %.2f", total))

Output:

[1] "Total: 16.20"

A width pads the value to that many characters: %5d pads on the left, %-6s pads on the right and %03d pads with zeros. %% prints a percent sign.

print(sprintf("[%5d]", 42))
print(sprintf("[%-6s]", "tea"))
print(sprintf("%03d", 7))
print(sprintf("%d%%", 85))

Output:

[1] "[   42]"
[1] "[tea   ]"
[1] "007"
[1] "85%"

sprintf() is vectorized: with vector arguments it returns one string per element. cat() with sep = "\n" prints each string on its own line.

items <- c("tea", "cake")
prices <- c(4, 12.5)
lines <- sprintf("%-5s %6.2f", items, prices)
cat(lines, sep = "\n")

Output:

tea     4.00
cake   12.50
challenge icon

Challenge

Easy

Complete receipt_line(item, qty, price). Return the item, the quantity and the line total (qty * price) in the form tea x3 = 13.50: the item, a space, x followed by the quantity, then = and the total with exactly two decimals.

The supplied code reads the item, the quantity and the price (one per line) and prints the returned value.

Try it yourself

receipt_line <- function(item, qty, price) {
  # Write your code here
  ""
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(receipt_line(input[1], as.integer(input[2]), as.numeric(input[3])), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler