简体   繁体   中英

Format number in R with both comma thousands separator and specified decimals

I'd like to format numbers with both thousands separator and specifying the number of decimals. I know how to do these separately, but not together.

For example, I use format per this for the decimals:

FormatDecimal <- function(x, k) {
  return(format(round(as.numeric(x), k), nsmall=k))
}
FormatDecimal(1000.64, 1)  # 1000.6

And for thousands separator, formatC :

formatC(1000.64, big.mark=",")  # 1,001

These don't play nicely together though:

formatC(FormatDecimal(1000.64, 1), big.mark=",")  
# 1000.6, since no longer numeric
formatC(round(as.numeric(1000.64), 1), nsmall=1, big.mark=",")
# Error: unused argument (nsmall=1)

How can I get 1,000.6 ?

Edit: This differs from this question which asks about formatting 3.14 as 3,14 (was flagged as possible dup).

format不是formatC

format(round(as.numeric(1000.64), 1), nsmall=1, big.mark=",") # 1,000.6

formatC(1000.64, format="f", big.mark=",", digits=1)

(对不起,如果我遗漏了什么。)

formattable provides comma :

library(formattable)

comma(1000.64, digits = 1) # 1,000.6

comma provides an elementary interface to formatC .

The scales library has a label_comma function:

scales::label_comma(accuracy = .1)(1000.64)
[1] "1,000.6"

With additional arguments if you want to use something other than a comma in the thousands place or another character instead of a decimal point, etc (see below).

Note: the output of label_comma(...) is a function to make it easier to use in ggplot2 arguments, hence the additional parentheses notation. This could be helpful if you're using the same format repeatedly:

my_comma <- scales::label_comma(accuracy = .1, big.mark = ".", decimal.mark = ",")

my_comma(1000.64)
[1] "1.000,6"

my_comma(c(1000.64, 1234.56))
[1] "1.000,6" "1.234,6"

Unfortunately for millions doesn't work or it requires something else. Any help?

formatC(1000000.64, big.mark=",")
[1] "1e+06"

Also, how do I get rid of the e+06 and show only commas?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM