Formatting Decimal places in R

前端 未结 12 2221
忘了有多久
忘了有多久 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条回答
  •  萌比男神i
    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

提交回复
热议问题