format()
format(x, trim = FALSE, digits = NULL, nsmall = 0, scientific = NA, ...) Returns:
character · Updated March 13, 2026 · String Functions formatting strings numbers format base
The format() function formats R objects for pretty printing. It converts objects to character vectors with controlled formatting.
Syntax
format(x, trim = FALSE, digits = NULL, nsmall = 0, scientific = NA,
big.mark = "", big.interval = 3, small.mark = "",
small.interval = 5, decimal.mark = ".", ...)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | object | required | An atomic object to format |
trim | logical | FALSE | If TRUE, removes leading whitespace |
digits | integer | NULL | Number of significant digits |
nsmall | integer | 0 | Minimum decimal places |
scientific | logical | NA | Force/disable scientific notation |
big.mark | character | "" | Separator for thousands |
decimal.mark | character | ”.” | Decimal separator |
... | arguments | passed to format.info() |
Examples
Basic number formatting
# Default formatting pads with spaces
format(123.456)
# [1] "123.456"
# Fix decimal places
format(123.456, nsmall = 2)
# [1] "123.46"
Controlling decimal places
# Minimum decimal places
format(c(1, 2.5, 3.14159), nsmall = 2)
# [1] "1.00" "2.50" "3.14"
# Significant digits
format(pi, digits = 5)
# [1] "3.1416"
Adding thousand separators
# Add commas as thousand separators
format(1234567, big.mark = ",")
# [1] "1,234,567"
format(1234567.89, big.mark = ",", nsmall = 2)
# [1] "1,234,567.89"
Trimming whitespace
# Default adds padding for alignment
format(1:5)
# [1] "1" "2" "3" "4" "5"
# Trim to remove padding
format(1:5, trim = TRUE)
# [1] "1" "2" "3" "4" "5"
Common Patterns
Pretty-printing tables
# Create aligned numeric output
df <- data.frame(
name = c("Sales", "Profit", "Growth"),
value = c(1234567, 98765, 0.12345)
)
df$value <- format(df$value, big.mark = ",", nsmall = 2)
print(df)
# name value
# 1 Sales 1,234,567.00
# 2 Profit 98,765.00
# 3 Growth 0.12
Combining with paste
# Create formatted output strings
x <- 1234.5678
paste0("The value is: ", format(x, nsmall = 2))
# [1] "The value is: 1234.57"
# Currency formatting
amount <- 1999.99
paste0("$", format(amount, big.mark = ",", nsmall = 2))
# [1] "$1,999.99"