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

sprintf

sprintf fills the blanks in a text template with your values, like a form letter where each blank is stamped with the right name. It also controls things like decimals.

In this page:

  1. sprintf
Syntax
r
sprintf("format %s %d %.2f", string_value, integer_value, decimal_value)

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))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing %d with a decimal number like 92.5, which gives an error; use %f or %.1f.
  2. Forgetting %% for a literal percent sign, so the format breaks.
  3. Passing fewer values than format specifiers, which gives too few arguments.
Chapter Summary
  • paste(), paste0(), nchar(), substr(), and case functions build and inspect strings.
  • gsub(), sub(), and strsplit() replace and split text.
  • sprintf() formats values into strings.
🔒

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.