Formatted Output with sprintf()
Control decimal places, padding, and alignment with sprintf format strings.
Formatted Output with sprintf() is a free R Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.
sprintf() Basics
sprintf() formats strings using a format string with placeholders. It works exactly like C's printf. The first argument is the format template; subsequent arguments fill the placeholders in order.
sprintf('There are %d items', 5)
sprintf('Hello, %s!', 'Alice')
sprintf('Price: %.2f', 9.999)Integer and String Placeholders
%d formats an integer, %s formats a string, and %f formats a floating-point number. Each placeholder is replaced in order by the corresponding argument.
name <- 'Bob'
age <- 34
score <- 88.5
sprintf('%s is %d years old with score %.1f', name, age, score)Controlling Decimal Places
%.2f means: format as float with exactly 2 decimal places. The number between . and f controls precision. This is ideal for currency, percentages, and scientific values.
pi_val <- 3.14159265
sprintf('%.0f', pi_val)
sprintf('%.2f', pi_val)
sprintf('%.5f', pi_val)
sprintf('$%.2f', 1234.5)Field Width and Padding
A number before the format letter sets the minimum field width. Values are right-aligned by default, padded with spaces on the left. This is useful for aligning columns in plain-text reports.
items <- c('Pen', 'Notebook', 'Stapler')
prices <- c(1.5, 4.99, 7.25)
for (i in seq_along(items)) {
cat(sprintf('%-10s $%6.2f\n', items[i], prices[i]))
}Left-Alignment with the - Flag
Prefix the width number with - to left-align text within the field. This is the standard way to produce left-justified columns in fixed-width text output.
# Right-aligned (default)
sprintf('%10s', 'hi')
# Left-aligned
sprintf('%-10s', 'hi')
# Practical: side-by-side
cat(sprintf('%-8s %5d\n', 'Alice', 42))
cat(sprintf('%-8s %5d\n', 'Bob', 7))Scientific Notation with %e and %g
%e forces scientific notation (e.g. 1.23e+04). %g automatically chooses the shorter of %f or %e — useful when values span many orders of magnitude.
x <- 0.000123456
y <- 123456789
sprintf('%e', x)
sprintf('%e', y)
sprintf('%g', x)
sprintf('%g', y)Zero Padding with 0 Flag
Prefix the width with 0 to pad numbers with leading zeros instead of spaces. This is commonly used for zero-padded IDs, dates, and file numbering schemes.
ids <- c(1, 12, 123, 1234)
sprintf('ID_%05d', ids)
# Date parts
sprintf('%04d-%02d-%02d', 2024, 5, 7)Percentage Formatting
To display a ratio as a percentage, multiply by 100 and use %.1f%%. The double %% inserts a literal percent sign in the output (a single % would be interpreted as the start of a placeholder).
pass_rate <- 0.8743
sprintf('Pass rate: %.1f%%', pass_rate * 100)
growth <- 0.0523
sprintf('Growth: +%.2f%%', growth * 100)sprintf() is Vectorized
When you pass a vector as an argument to sprintf(), it automatically iterates over the vector and returns one formatted string per element. The format string itself is recycled.
products <- c('Apple', 'Banana', 'Cherry')
prices <- c(0.99, 0.59, 2.49)
sprintf('%-8s costs $%.2f', products, prices)Multiple Placeholders, Multiple Arguments
Each placeholder consumes one argument in order. You can mix %d, %f, and %s freely in a single format string, and all vector arguments are recycled to the longest length.
months <- c('Jan', 'Feb', 'Mar')
revenue <- c(12500, 9800, 15300)
growth <- c(0.05, -0.12, 0.18)
sprintf('%s: $%d (growth: %+.1f%%)',
months, revenue, growth * 100)sprintf() vs paste() — When to Use Each
Use paste()/paste0() for simple concatenation; use sprintf() when you need precise numeric formatting (decimal places, widths, padding). sprintf() is more verbose but gives you complete control over number appearance.
val <- 1234567.891
# paste: no formatting control
paste('Total:', val)
# sprintf: formatted as currency
sprintf('Total: $%,.2f', val)
# With manual formatting
sprintf('Total: $%15.2f', val)Quick Check
Which format code in sprintf() inserts a literal percent sign % into the output?
sprintf() Key Takeaways
Key takeaways for sprintf():
%dinteger,%ffloat,%sstring,%escientific,%gauto%.2f= 2 decimal places;%10.2f= width 10, 2 decimals%-10s= left-align in 10-char field;%05d= zero-pad to 5 digits%%= literal percent sign in outputsprintf()is vectorized over its arguments- Prefer
sprintf()overpaste()when numeric formatting precision matters
x <- 0.87654
cat(sprintf('Default f : %f\n', x))
cat(sprintf('2 decimals : %.2f\n', x))
cat(sprintf('Percentage : %.1f%%\n', x * 100))
cat(sprintf('Scientific : %e\n', x))
cat(sprintf('Auto : %g\n', x))Learn R with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 43
- Lessons
- 159
Frequently Asked Questions
Is the “Formatted Output with sprintf()” lesson free?
Yes — any 3 lessons of the R Academy learning path, including “Formatted Output with sprintf()”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.
What will I learn in “Formatted Output with sprintf()”?
Control decimal places, padding, and alignment with sprintf format strings. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.
How long does the “Formatted Output with sprintf()” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Building Strings with paste() and paste0()
- Formatted Output with sprintf()
- Displaying Output with cat() and print()
- String Padding and Alignment