VOOZH about

URL: https://www.geeksforgeeks.org/r-language/formatting-numbers-and-strings-in-r-programming-format-function/

⇱ Formatting Numbers and Strings in R Programming - format() Function - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Formatting Numbers and Strings in R Programming - format() Function

Last Updated : 30 Apr, 2026

In R programming, the format() function formats numbers, strings and dates to meet presentation needs. It gives formatting features to modify the display of numeric values, strings and date/time information. This function is applied to regulate the number of decimal places, alignment, scientific notation, etc. The format() function makes data display in the required format, making it easier to read and appropriate for reporting or data analysis.

Syntax:

format(x, digits, nsmall, scientific, width, justify = c("left", "right", "center", "none")) 

Parameters:

  • x: is the vector input.
  • digits: is the total number of digits displayed.
  • nsmall: is the minimum number of digits to the right of the decimal point.
  • scientific: is set to TRUE to display scientific notation.
  • width: indicates the minimum width to be displayed by padding blanks in the beginning.
  • justify: is the display of the string to left, right or center.

String formatting

The format() function can also center strings according to the width and alignment given.

Example: Aligning Strings


Output
[1] "GFG "
[1] " GFG "
[1] " GFG"

Number formatting

The format() method can also be applied to control the display of numbers, such as specifying decimal places, scientific notation and rounding numbers.

Example 1: Rounding Numbers and Controlling Decimal Places


Output
[1] "12.35"
[1] "12.3457"
[1] "12.34568"
[1] "12.3456789"

Example 2: Formatting Numbers with Scientific Notation


Output
[1] "1234"
[1] "12.34568"
[1] "1.234568e+01"
[1] "12.34568"

Handling Categorical Labels in R

When working with categorical data coded as numeric values (e.g., 1, 2, 3, 4), the format() function is not suitable for assigning meaningful labels. Instead, we should use factors to map values to descriptive categories.

Output:

age_group

Age 0-17 2

Age 18-44 2

Age 45-64 2

Age 65 or older 1

Date and Time formatting

The format() function can also be utilized to format date-time objects in R. You can convert Date or POSIX objects to tailored string representations.

Example 1: Formatting Date-Time Objects


Output
[1] "2025-04-23 09:16:49"

Example 2: Formatting Dates with Full Month Name


Output
[1] "June 27, 2023"

Date-Time Format Codes:

  • %Y: Year with century as a decimal number.
  • %B: Full month name.
  • %d: Day of the month as a decimal number.
Comment
Article Tags:

Explore