Formatting Decimal places in R

前端 未结 12 2063
忘了有多久
忘了有多久 2020-11-22 01:42

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?

相关标签:
12条回答
  • 2020-11-22 01:58

    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
    
    0 讨论(0)
  • 2020-11-22 01:59

    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.

    0 讨论(0)
  • 2020-11-22 02:00

    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)
    
    0 讨论(0)
  • 2020-11-22 02:01

    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

    0 讨论(0)
  • 2020-11-22 02:05

    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).

    0 讨论(0)
  • 2020-11-22 02:06

    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
    
    0 讨论(0)
提交回复
热议问题