Home > Software design >  R sprintf() adding thousand separator
R sprintf() adding thousand separator

Time:12-28

How can sprintf() function be used to print thousand separators in R? For example if:

x<-123456.98765

then if I want to print 0 decimal points after the whole number I use:

sprintf("%.0f", x)

and you will get: "123457"

But how to add with sprintif thousand separators and currency symbol at the end to get the following results: 123.457 $

CodePudding user response:

Update 2: After OP clarification:

paste0(formatC(as.numeric(x), format="f", digits=0, big.mark=","), "$")
[1] "123,457$"

With sprintf:

sprintf("%s $", format(x, big.mark=","))
[1] "123,457 $"

Update 1: Please see comment of jay.sf:

We could use prettyNum:

paste0(prettyNum(as.integer(x), big.mark=",", scientific=FALSE), ' $')


OR dollar_format:

https://www.rdocumentation.org/packages/scales/versions/0.4.1/topics/dollar_format

usd <- dollar_format(prefix = "", suffix = "$")
usd(x)

[1] "123,457$"

CodePudding user response:

Use format() and big.mark="," instead

format(x, big.mark=",", nsmall=2)

Wrap that in a paste() to get the currency symbol too

paste0(format(x, big.mark=",", nsmall=2), "$")

To return

"123,456.99$"

If you must use sprintf() then

sprintf("%s$", format(x, big.mark=",", nsmall=2))
  •  Tags:  
  • r
  • Related