Formatting Decimal places in R

前端 未结 12 2066
忘了有多久
忘了有多久 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 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).

提交回复
热议问题