The sprintf() function in R is used to print the formatted strings. For example, use the sprintf(“%f”, x) function to format a numeric value x with six digits after the decimal point.
Syntax
sprintf(fmt, x)
Parameters
- fmt: It is a character vector of format strings, each of up to 8192 bytes.
- x: It is the value to format.
Return Value
It returns the character vector of length that of the longest input.
Example 1: Format decimal places

The above figure shows that the sprintf() function is used to format and display the value of x with only 2 digits after the decimal point. Let’s implement it into the program.
# Define value
x <- 21.41347382
# Only display 2 digits after decimal place
sprintf("%.2f", x)
Output
[1] "21.41"
Example 2: Format digits before decimal point
Figure 2: Use sprintf() function to format digits before decimal point
We used the sprintf() function to format and display the value of x as a floating-point number with no digits after the decimal point while ensuring a minimum width of 10 characters for the output.
# Define value
x <- 1219191919192121.48484848
sprintf("%10.f", x)
Output
[1] "1219191919192122"
Example 3: Format value using Scientific Notation

rv <- 19.211
sprintf("%e", rv)
You can return the upper case E to the RStudio console.
data <- 19.211
sprintf("%E", data)
Output
[1] "1.921100E+01"
Example 4: Format digits before the decimal point
Figure 4: Format digits before the decimal point
rv <- 19.211
sprintf("%1.0f", rv)
Output
[1] "19"
Example 5: Format Digits After Decimal Point
data <- 21.19461118
#only display 2 digits after decimal place
sprintf("%.2f", data)
Output
[1] "21.19"
Example 6: Format a value in String
data <- 21.19461118
sprintf("I am away %.1f miles from Perth city", data)
Output
[1] "I am away 21.2 miles from Perth city"
You can also format multiple values in a string:
x1 <- 21.11
x2 <- 11.21
sprintf("I rode my car %.1f miles and then ran %.2f miles", x1, x2)
Output
[1] "I rode my car 21.1 miles and then ran 11.21 miles"
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.