Format Number of Decimal Places in R (2 Example Codes)

 

This tutorial explains how to control the number of decimal places within the R programming language. The table of contents looks as follows:

 

Figure 1 shows an overview of three different alternatives for controlling decimal places in R.

 

Format Decimal Places R Overview

Figure 1: Format Decimal Places in R (Overview).

 

However, in the following examples I will explain these alternatives in more detail. So let’s move directly to the examples…

 

Create Example Data

Let’s first have a look at the default specifications of R, before we start with the examples. Consider the following numeric data object:

x <- 10.76567759879643247        # Create example data object

If we print this number, the RStudio console returns the following:

x                                # Print example data
# 10.76568

As you can see: A number with five decimal places.

In the following examples, you will learn how to format these decimals in R. So let’s continue with the examples…

 

Example 1: Apply format Function to Control Decimal Places of One Specific Number

If we want to format the decimal places of one specific number (or a vector of numbers), we can use the format function in combination with the round function and the specification nsmall. Consider the following R syntax:

format(round(x, 3), nsmall = 3)  # Apply format function
# "10.766"

As you can see: The number of digits after the decimal point was reduced to three.

Note: The output of the format function is a character string. If we want to do calculations with this output, we need to convert it back to the numeric class first.

 

Example 2: Format Decimal Places with sprintf Function

The sprintf R function also provides the possibility to control decimal places of a certain number or a numeric vector. Let’s have a look at the R syntax:

sprintf(x, fmt = '%#.3f')        # Apply sprintf function
# "10.766"

The output is the same as before. Again, we created a character string with three decimal places.

 

Example 3: Change Number of Digits in Global R Options

In this example, I’ll show you how to format the general options for printing digits in RStudio. Consider the following R syntax:

options(digits = 5)              # Modify global options

Now let’s print our example data again:

x                                # Print example data
# 10.766

As you can see, the console output is a number with only three decimal places (in contrast to the five decimal places that we had before).

With the previous R code (i.e. options(digits = 5)), we changed the number of maximum digits to 5. In our specific example, 2 digits before the decimal point and 3 digits after the decimal point. If there would be more digits before the decimal point, the number of digits after the decimal point would be reduced (e.g. 1000.8).

Note: The amount of digits has now been changed for our entire R session. If we would like to change the options back to the default specification, we would have to restart RStudio, or we would have to save the default specification in the forefront.

 

Tutorial Video & Further Resources for Dealing with Numbers in R

In case you need further explanations on the code of this page, you may check out the following YouTube video on the Statistics Globe YouTube channel. It explains the syntax of this article in some more detail:

 

 

If you want to learn more about the handling of numbers in R, I can recommend the following video of the YouTuber Anthony Damico. In the video, he explains different ways how to change options and global settings in R.

 

 

Besides the video, you might also want to read more tutorials on statisticsglobe.com. In this case, you could have a look at the following list of tutorials:

This tutorial showed you how to format the number of decimal places in R. Do you have any feedback or further questions? Let me know in the comments below.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


7 Comments. Leave new

  • Hi!

    Im trying to convert a character variable with values such as (1,234 , 123 etc.) to numeric with as.numeric but it doesn’t work? I’m keep getting warning message about NAs introduced by coercion and I think its because of the decimals because I have dropped all NA in that variable.

    Reply
    • Hello,

      Sorry for the late response. I am not sure if you could already fix it but the answer is that it is due to formatting instead of decimals. Try with “1.234” once:)

      Regards,
      Cansu

      Reply
      • im not sure I understand you. I have not defined the values myself so how should I change the formatting? its too many observations for me to change manually.

        Thank you!

        Reply
        • Hello again,

          What about trying this? I hope this helps.

          df<-data.frame(x=c("1,12", "13,4", "1,789"), y=c("1,1", "17,4", "1,89"))
          df
           
          #      x    y
          # 1  1,12  1,1
          # 2  13,4 17,4
          # 3 1,789 1,89
           
          df$x<-as.numeric(gsub(",", ".", gsub("\\.", "", df$x)))
          df$x
           
          # [1]  1.120 13.400  1.789

          Regards,
          Cansu

          Reply
          • I only get missing values when I try that on my data and even with your own example? what could be wrong?

          • df$x<-as.numeric(gsub(",", ".", df$x)) is working for the positive values but all negative values get NA?

          • Hello,

            It works for me for the negative values as well. Could you please check the following script in your R environment?

            df<-data.frame(x=c("1,12", "-13,4", "-1,789"), y=c("1,1", "17,4", "1,89"))
            df
             
            #       x    y
            # 1   1,12  1,1
            # 2  -13,4 17,4
            # 3 -1,789 1,89
            df$x<-as.numeric(gsub(",", ".", gsub("\\.", "", df$x)))
            df$x
             
            # [1]   1.120 -13.400  -1.789

            Regards,
            Cansu

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top