sprintf
In this page:
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
name <- "Alice"
score <- 92.5
cat(sprintf("Name: %s, Score: %.1f%%\n", name, score))
cat(sprintf("Padded number: %05d\n", 42))
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: