77

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

Community
  • 1
  • 1
Max Ghenis
  • 14,783
  • 16
  • 84
  • 132

4 Answers4

145

format not formatC:

format(round(as.numeric(1000.64), 1), nsmall=1, big.mark=",")  # 1,000.6
display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
Max Ghenis
  • 14,783
  • 16
  • 84
  • 132
26
formatC(1000.64, format="f", big.mark=",", digits=1)

(sorry if i'm missing something.)

Greg Minshall
  • 547
  • 5
  • 6
11

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"
LMc
  • 12,577
  • 3
  • 31
  • 43
8

formattable provides comma:

library(formattable)

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

comma provides an elementary interface to formatC.

Werner
  • 14,324
  • 7
  • 55
  • 77