[r] Formatting Decimal places in R

I have a number, for example 1.128347132904321674821 that I would like to show as only two decimal places when output to screen (or written to a file). How does one do that?

x <- 1.128347132904321674821

EDIT:

The use of:

options(digits=2)

Has been suggested as a possible answer. Is there a way to specify this within a script for one-time use? When I add it to my script it doesn't seem to do anything different and I'm not interested in a lot of re-typing to format each number (I'm automating a very large report).

--

Answer: round(x, digits=2)

This question is related to r formatting rounding r-faq

The answer is


The function formatC() can be used to format a number to two decimal places. Two decimal places are given by this function even when the resulting values include trailing zeros.


If you prefer significant digits to fixed digits then, the signif command might be useful:

> signif(1.12345, digits = 3)
[1] 1.12
> signif(12.12345, digits = 3)
[1] 12.1
> signif(12345.12345, digits = 3)
[1] 12300

I'm using this variant for force print K decimal places:

# format numeric value to K decimal places
formatDecimal <- function(x, k) format(round(x, k), trim=T, nsmall=k)

You can format a number, say x, up to decimal places as you wish. Here x is a number with many decimal places. Suppose we wish to show up to 8 decimal places of this number:

x = 1111111234.6547389758965789345
y = formatC(x, digits = 8, format = "f")
# [1] "1111111234.65473890"

Here format="f" gives floating numbers in the usual decimal places say, xxx.xxx, and digits specifies the number of digits. By contrast, if you wanted to get an integer to display you would use format="d" (much like sprintf).


if you just want to round a number or a list, simply use

round(data, 2)

Then, data will be round to 2 decimal place.


Something like that :

options(digits=2)

Definition of digits option :

digits: controls the number of digits to print when printing numeric values.

here's my approach from units to millions. digits parameter let me adjust the minimum number of significant values (integer + decimals). You could adjust decimal rounding inside first.

number <-function(number){
  result <- if_else(
    abs(number) < 1000000,
    format(
      number, digits = 3,
      big.mark = ".",
      decimal.mark = ","
    ),
    paste0(
      format(
        number/1000000,
        digits = 3,
        drop0trailing = TRUE,
        big.mark = ".",
        decimal.mark = ","
      ),
      "MM"
    )
  )
  # result <- paste0("$", result)
  return(result)
}

Note that numeric objects in R are stored with double precision, which gives you (roughly) 16 decimal digits of precision - the rest will be noise. I grant that the number shown above is probably just for an example, but it is 22 digits long.


Check functions prettyNum, format

to have trialling zeros (123.1240 for example) use sprintf(x, fmt='%#.4g')


Looks to me like to would be something like

library(tutoR)
format(1.128347132904321674821, 2)

Per a little online help.


You can try my package formattable.

> # devtools::install_github("renkun-ken/formattable")
> library(formattable)
> x <- formattable(1.128347132904321674821, digits = 2, format = "f")
> x
[1] 1.13

The good thing is, x is still a numeric vector and you can do more calculations with the same formatting.

> x + 1
[1] 2.13

Even better, the digits are not lost, you can reformat with more digits any time :)

> formattable(x, digits = 6, format = "f")
[1] 1.128347

for 2 decimal places assuming that you want to keep trailing zeros

sprintf(5.5, fmt = '%#.2f')

which gives

[1] "5.50"

As @mpag mentions below, it seems R can sometimes give unexpected values with this and the round method e.g. sprintf(5.5550, fmt='%#.2f') gives 5.55, not 5.56


Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to rounding

How to round a numpy array? How to pad a string with leading zeros in Python 3 Python - round up to the nearest ten How to round a Double to the nearest Int in swift? Using Math.round to round to one decimal place? How to round to 2 decimals with Python? Rounding to 2 decimal places in SQL Rounding to two decimal places in Python 2.7? Round a floating-point number down to the nearest integer? Rounding BigDecimal to *always* have two decimal places

Examples related to r-faq

What does "The following object is masked from 'package:xxx'" mean? What does "Error: object '<myvariable>' not found" mean? How do I deal with special characters like \^$.?*|+()[{ in my regex? What does %>% function mean in R? How to plot a function curve in R Use dynamic variable names in `dplyr` Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning? How to select the row with the maximum value in each group R data formats: RData, Rda, Rds etc