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

Max Ghenis picture Max Ghenis · Apr 6, 2015 · Viewed 60.7k times · Source

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

Answer

Max Ghenis picture Max Ghenis · Apr 6, 2015

format not formatC:

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