Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

format

r

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

like image 217
Max Ghenis Avatar asked Apr 06 '15 05:04

Max Ghenis


2 Answers

format not formatC:

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

like image 171
Max Ghenis Avatar answered Sep 24 '22 11:09

Max Ghenis


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

(sorry if i'm missing something.)

like image 45
Greg Minshall Avatar answered Sep 21 '22 11:09

Greg Minshall