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

RFormat

R Problem Overview


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

R Solutions


Solution 1 - R

format not formatC:

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

Solution 2 - R

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

(sorry if i'm missing something.)

Solution 3 - R

formattable provides comma:

library(formattable)

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

comma provides an elementary interface to formatC.

Solution 4 - R

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMax GhenisView Question on Stackoverflow
Solution 1 - RMax GhenisView Answer on Stackoverflow
Solution 2 - RGreg MinshallView Answer on Stackoverflow
Solution 3 - RWernerView Answer on Stackoverflow
Solution 4 - RLMcView Answer on Stackoverflow