Max Ghenis
Max Ghenis

Reputation: 15803

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

Upvotes: 86

Views: 135932

Answers (5)

andschar
andschar

Reputation: 3973

Working with datatables you can use DT::formatRound() (The data type will remain numeric):

DT::datatable(
  data.frame(value = 1000.64),
  rownames = FALSE
) |>
  DT::formatRound(1, digits = 1)

NOTE This answer is a bit beyond the scope of the OP's question, but when working with datatables tables it's the way to go.

Upvotes: 0

LMc
LMc

Reputation: 18642

The scales package 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"

Upvotes: 16

Max Ghenis
Max Ghenis

Reputation: 15803

format not formatC:

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

Upvotes: 158

Werner
Werner

Reputation: 15065

formattable provides comma:

library(formattable)

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

comma provides an elementary interface to formatC.

Upvotes: 8

Greg Minshall
Greg Minshall

Reputation: 627

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

(sorry if i'm missing something.)

Upvotes: 29

Related Questions