← Back to R Course | Chapter 6: Strings | Lesson 7 of 7

sprintf

In this page:

  1. sprintf

sprintf

sprintf() formats values into a string using C-style format specifiers, like %s for strings, %d for integers, and %.2f for fixed decimal places. It gives precise control over formatting that paste() doesn't offer, such as zero-padding or fixed-width fields. This is R's equivalent of printf-style formatting found in many other languages.

Note: sprintf("%.2f", x) is the standard way to format a number to exactly 2 decimal places for display.

Example: sprintf

markup
name <- "Alice"
score <- 92.5

cat(sprintf("Name: %s, Score: %.1f%%\n", name, score))
cat(sprintf("Padded number: %05d\n", 42))
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.