# Formatting Numbers and Strings in R Programming – format() Function

• Last Updated : 25 Oct, 2021

format() function in R Programming Language is used to format strings and numbers in a specified style.

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 in R

Example: In this example, we are going will work with string formatting in R programming using format() method.

## R

 `# Placing string in the left side``result1 <- ``format``(``"GFG"``, width = 8,  justify = ``"l"``)` `# Placing string in the center``result2 <- ``format``(``"GFG"``, width = 8,  justify = ``"c"``)` `# Placing string in the right``result3 <- ``format``(``"GFG"``, width = 8,  justify = ``"r"``)` `# Getting the different string placement``print``(result1)``print``(result2)``print``(result3)`

Output:

```[1] "GFG     "
[1] "  GFG   "
[1] "     GFG"```

## Number formatting in R

Here we will use format() method for number formatting in R programming.

Example 1:

## R

 `# R program to illustrate``# format function` `# Calling the format() function over``# different arguments` `# Rounding off the specified digits``# into 4 digits``result1 < - ``format``(12.3456789, digits=4)``result2 < - ``format``(12.3456789, digits=6)``print``(result1)``print``(result2)` `# Getting the specified minimum number of digits``# to the right of the decimal point.``result3 < - ``format``(12.3456789, nsmall=2)``result4 < - ``format``(12.3456789, nsmall=7)``print``(result3)``print``(result4)`

Output:

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

Example 2:

## R

 `# R program to illustrate``# format function` `# Calling the format() function over``# different arguments` `# Getting the number in the string form``result1 < - ``format``(1234)``result2 < - ``format``(12.3456789)``print``(result1)``print``(result2)` `# Display numbers in scientific notation``result3 < - ``format``(12.3456789, scientific=``TRUE``)``result4 < - ``format``(12.3456789, scientific=``FALSE``)``print``(result3)``print``(result4)`

Output:

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

My Personal Notes arrow_drop_up