Skip to main content
v2026.11,986 entries · CC-BY 4.0

sprintf in R: Syntax, Format Specifiers and Examples

How sprintf() works in R: fmt syntax, %d %f %s %e %g specifiers, width and precision, vectorised examples and the errors to expect.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

In R, sprintf(fmt, ...) builds a character vector by inserting values into a format string: each conversion such as %d, %f or %s in fmt is replaced by the next argument, formatted as you specify. The R manual describes it as a wrapper for the C function sprintf that returns a character vector containing a formatted combination of text and variable values. The same function is what people search for as “sprintf r”.

What sprintf does in research code

Analysis scripts end up as text: table cells, figure captions, log lines, file names and sentences such as “mean = 12.3 (n = 30)”. sprintf() keeps the wording in one template and the numbers in separate arguments, so the number of decimals, the padding and the order of values are controlled in a single place. Because it is vectorised, one call can format a whole column of a data frame. It is part of base R, so it needs no package and behaves the same in an R script, an R Markdown or Quarto document and an interactive session.

It is also the tool for reproducible rounding at the point of display. A model estimate stored as 0.123456789 stays untouched in the object; only the string you print is cut to three decimals. That separation (full precision in the data, formatted text in the report) is the main reason to prefer sprintf() over editing numbers by hand. If you are new to the surrounding language, the guides on R data types and coercion and data frames in R cover the objects you will pass in. Users coming from MATLAB will find the same family of format codes, with a few differences, in sprintf in MATLAB.

Install or access

Nothing needs installing beyond R itself. sprintf and its companion gettextf live in the base package, which is attached in every R session, so there is no library() call. R is distributed from the Comprehensive R Archive Network (CRAN) at cran.r-project.org. To read the authoritative help page for your installed version, run ?sprintf or help("sprintf") at the console. The formal description of the function is the base R documentation page for sprintf, cited in the sources below.

Syntax and arguments

The documented usage is:

sprintf(fmt, ...)
gettextf(fmt, ..., domain = NULL, trim = TRUE)
  • fmt is a character vector of format strings. Each string may be up to 8192 bytes long.
  • ... holds the values to insert. Only logical, integer, real (double) and character vectors are supported, with some coercion, and the documentation allows up to 100 values.
  • The return value is a character vector with the length of the longest input. If any input is declared UTF-8, the result is declared UTF-8 too.

gettextf() is a convenience wrapper that translates the format string first and then calls sprintf(); for ordinary analysis scripts you will use sprintf() directly.

The anatomy of a conversion specification

A conversion specification starts with % and ends with one of the conversion characters a A d i f e E g G o s x X %. Between them you may place flags, a width and a precision, written m.n where m is the minimum field width and n is the precision. Their meaning depends on the conversion: for f the precision is the number of digits after the decimal point, for g it is the number of significant digits, and for s it limits the number of bytes taken from the string.

The flags documented in the manual are:

  • - left-adjusts the output within its field;
  • + always prints a sign for numbers;
  • a space prefixes positive numbers with a space;
  • 0 pads numbers with leading zeros (zero-padding of character strings is platform dependent);
  • # selects an alternate output form.

The data table below lists every conversion the R manual defines, the input types it accepts and what it does. Two further features are worth knowing: %% prints a literal percent sign, and a * in place of the width or precision takes that number from the argument list (the manual notes it cannot be used for both in the same specification).

Step-by-step: format numbers for a results sentence

The steps below build the kind of line a methods or results section needs. Each output shown follows directly from the documented C-style behaviour of the specifiers.

  1. Write the template with one conversion per value. For a group mean to one decimal place and a sample size, use %s for the label, %.1f for the mean and %d for the count.
  2. Pass the values in the same order.
    sprintf("Group %s: mean = %.1f (n = %d)", c("A", "B"), c(12.34, 7.86), c(30L, 28L))
  3. Read the result. The three vectors have equal length, so the call returns two strings: "Group A: mean = 12.3 (n = 30)" and "Group B: mean = 7.9 (n = 28)".
  4. Print it for a report or a log. sprintf() returns the strings rather than printing them with line breaks; wrap the call in cat(..., sep = "\n") or writeLines() when you want one line per element.
  5. Apply the template to a column. Inside a data frame workflow, pass the columns as the arguments, for example sprintf("%.2f", df$estimate), and store the result in a new character column. The original numeric column keeps its full precision.

Worked examples drawn from the R manual

The examples below use the constant pi and the examples published in the R documentation for sprintf, so you can check them against the manual.

Decimals, width and signs

sprintf("%.3f", pi)      # "3.142"
sprintf("%5.1f", pi)     # "  3.1"   (width 5, one decimal)
sprintf("%05.1f", pi)    # "003.1"   (zero-padded to width 5)
sprintf("%+f", pi)       # "+3.141593"  (default six decimals, sign shown)
sprintf("%-10f", pi)     # left-adjusted in a 10-character field
sprintf("%e", pi)        # "3.141593e+00"
sprintf("%g", pi)        # "3.14159"  (six significant digits)

The default precision for f, e and g is six, which is why %f prints six decimals and %g six significant digits. The manual adds that %g switches to exponential form when the exponent is less than -4 or greater than or equal to the precision; its own example contrasts sprintf("%g", 1e6*pi), which comes out in exponential form, with sprintf("%.9g", 1e6*pi), which stays fixed.

A literal percent sign

sprintf("%.0f%% said yes (out of a sample of size %.0f)", 66.666, 3)
# "67% said yes (out of a sample of size 3)"

Here %.0f prints a number with no decimals, and %% prints the percent sign itself. Using %.0f for the sample size also works when the value is stored as a double, which leads to the next point about %d.

Reusing and reordering arguments

sprintf("second %2$1.0f, first %1$5.2f, third %3$1.0f", pi, 2, 3)
# "second 2, first  3.14, third 3"

The manual documents n$ notation, where n runs from 1 to 99, for selecting arguments by position. It lets one argument be used twice or the order changed (useful for translated templates), but an argument reused this way must be used with the same type.

Width and precision from arguments

sprintf("precision %.*f, width '%*.3f'", 3, pi, 8, pi)
# "precision 3.142, width '   3.142'"

Output and how to read it

The result of sprintf() is always a character vector, so at the console it prints with an index and quotation marks, for example [1] "3.142". The quotes are display only. The string itself contains just the characters, which is what cat() or writeLines() write to a file or the console. Because the result is text, it cannot be used directly in arithmetic afterwards: convert with as.numeric() if you need a number again, and remember that doing so reads the rounded text, not the original value.

Check three things when you read the output. First, the length: it equals the length of the longest argument, and a zero-length argument gives a zero-length result. Second, the number of decimals: precision after a decimal point in f is exact, so %.2f always prints two decimals, padding with zeros where needed. Third, the column alignment: a width such as %10s right-aligns text in 10 characters and %-10s left-aligns it, but, according to the manual, width and precision for %s are interpreted as bytes, not characters, so strings with accented or non-Latin characters can look misaligned.

Vectors and recycling

All arguments are recycled to the length of the longest, and the formatting is done in parallel. The manual’s example is:

sprintf("%s %d", "test", 1:3)
# "test 1" "test 2" "test 3"

This is the behaviour that replaces a loop. A construct such as the one explained in for loops in R is rarely needed just to format a vector; sprintf() already runs along it. The flip side is that recycling is silent, so a vector of length 2 combined with one of length 3 is not an error in the usual sense; check lengths when the arguments come from different objects. If you pass more arguments than the format uses, R gives a warning, and the manual notes that %.0s can be used to skip an argument deliberately.

Troubleshooting

Error with %d and a decimal number

%d and %i accept integers, and numeric (double) values only when they are integer-valued. The manual’s example is sprintf("%s is %i feet talln", "Sven", 7.1), which gives an error, while the same call with 7 works. Use %f (or %.0f) for doubles that may have a fractional part, or round deliberately before formatting.

Rounding differs from round()

The documentation for round() warns that rounding to decimal digits in binary arithmetic is non-trivial, because most decimal fractions are not exactly representable in double precision. It also states that from R 4.0.0 round(x, d) follows a different algorithm from earlier versions, and describes the result as contrary to sprintf() or format() based rounding. So a value printed through %.2f and the same value passed through round(x, 2) can differ in the last digit for some inputs. For reported statistics, choose one route and use it consistently across the whole document.

Wrong or unusual format strings

The manual warns that the format is passed to the operating system’s sprintf, that incorrect formats can crash the R process, and that behaviour not documented in the manual is platform dependent. Stay within the conversions in the data table, and avoid exotic flag combinations in code that other people will run on a different system.

Length limits

Each format string is limited to 8192 bytes, and a call takes up to 100 values. Long reports are better built from several shorter calls joined with paste0().

Text such as NA and -0

For %s, an NA value is written as the string “NA”. The manual also notes that signed zeros may be printed as -0, which can surprise you in a table of small negative estimates that round to zero.

sprintf, paste and the free alternatives

You do not need extra software for any of the alternatives below: all are in base R. The table is built from the functions that the sprintf manual lists under “See also” and from the paste manual.

Function Best for How it differs from sprintf
paste(..., sep = " ", collapse = NULL) Joining strings and values into one text Concatenates vectors after converting them to character; no format codes, so number of decimals is not controlled
paste0(...) Joining with no separator Same as paste without a sep argument
formatC() C-style number formatting by argument (width, digits, format) Listed in the sprintf manual’s See also; takes formatting options as arguments instead of a template string
format() Formatting objects for printing Rounding is described in the round manual as following the same approach as sprintf
gettextf() Translatable messages Wrapper that translates fmt and then calls sprintf()

As a rule of thumb: use paste0() when you only join text, and sprintf() as soon as you care how a number appears. A template is also easier to review than a chain of paste0() calls and round() calls, because a reader sees the whole sentence in one string. If you wrap a template in your own helper, see writing functions in R.

Reporting practice for researchers

Three habits keep generated text trustworthy. Format only at the last step, from the full-precision object, rather than formatting then re-reading the text. Put the precision in one named constant or helper so the same number of decimals is used for every table and caption. And generate the sentence from the data in the analysis script, so a rerun updates the manuscript text along with the figures instead of leaving hand-copied numbers behind.

Frequently asked questions

What does sprintf do in R?

It returns a character vector in which the conversion specifications in fmt (such as %d, %f and %s) are replaced by the formatted values of the remaining arguments. It is a wrapper for the C function of the same name.

How do I print a percent sign with sprintf in R?

Write %% in the format string. For example, sprintf("%.0f%%", 66.666) returns “67%”.

How many decimals does %f print by default?

Six. A precision such as %.2f changes that, and a precision of 0 suppresses the decimal point.

Is sprintf vectorised in R?

Yes. Arguments are recycled to the length of the longest and formatted in parallel, so sprintf("%s %d", "test", 1:3) returns three strings.

Why does sprintf with %d fail on 7.1?

Numeric values are accepted by %d only when they are integer-valued. Use %f for non-integers.

What is the difference between sprintf and paste in R?

paste() converts values to character and joins them; sprintf() additionally lets you set decimals, width, padding and signs through format specifications.

Sources

  • R Core Team, R documentation for sprintf (base package), R-devel manual: https://stat.ethz.ch/R-manual/R-devel/library/base/html/sprintf.html (read 2026-11-14).
  • R Core Team, R documentation for paste: https://stat.ethz.ch/R-manual/R-devel/library/base/html/paste.html (read 2026-11-14).
  • R Core Team, R documentation for round and signif: https://stat.ethz.ch/R-manual/R-devel/library/base/html/Round.html (read 2026-11-14).
  • The Comprehensive R Archive Network, An Introduction to R: https://cran.r-project.org/doc/manuals/r-release/R-intro.html (read 2026-11-14).

Data: R sprintf() conversion specifiers: accepted input types and output

Compiled from the base R documentation page for sprintf (R-devel manual): each conversion character, the input types it accepts, how other types are coerced, and what it produces.

R sprintf() conversion specifiers: accepted input types and output
ConversionValue typeAccepted input and coercionOutput
%d, %iIntegerInteger; integer-valued numerics are coerced; logical gives 0, 1 or NADecimal integer
%oIntegerSame input rules as %dOctal
%x, %XIntegerSame input rules as %dHexadecimal (lower or upper case)
%fRealNon-double input is coerced with as.doubleFixed point; default 6 decimals; precision 0 suppresses the point
%e, %ERealNon-double input is coerced with as.doubleExponential notation
%g, %GRealNon-double input is coerced with as.double%e/%E if exponent < -4 or >= precision, else %f; precision = significant digits (default 6)
%a, %ARealNon-double input is coerced with as.doubleHexadecimal binary representation
%sCharacterNon-character input is coerced with as.character; NA gives "NA"String; width and precision count bytes
%%NoneNo argument consumedA literal percent sign

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about sprintf in R: Syntax, Format Specifiers and Examples

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →