Number formatting in R

Here we will use the 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"

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

Formatting in R can be formatted into the necessary representations using the flexible R function format(). It can be used with many different types of objects, including character strings, date/time data, and numeric numbers. By providing formatting options, the function enables us to regulate how the result looks.

The format() function lets us format numerical numbers by allowing us to select the number of decimal places (nsmall argument), the thousands of separators to be used (big. mark argument), the decimal mark (decimal. mark argument), and other formatting parameters. With the help of this, we can format strings to adhere to a particular locale’s conventions or satisfy desired presentation requirements.

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.

Similar Reads

String formatting in R

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

Number formatting in R

...

Date and Time formatting in R

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