简体   繁体   中英

Return a number as a comma-delimited string

Background

Due to a bug in Renjin , the format family of functions are unavailable, but sprintf works.

Code

Here is a replacement function that converts a number to a comma-delimited string:

commas <- function( n ) {
  s <- sprintf( "%03.0f", n %% 1000 )
  n <- n %/% 1000

  while( n > 0 ) {
    s <- concat( sprintf( "%03.0f", n %% 1000 ), ',', s )
    n <- n %/% 1000
  }

  gsub( '^0*', '', s )
}

Question

While the code does the job, how can the implementation be sped up? That is, how can the code be written so as to make use of R vernacular ( without using format , formatC , prettyNum , and the like) and without broken Renjin packages (ie, no dependencies)?

There is a slick one-liner you can use to add thousands comma separators to the whole number digits of a number, without adding them to the decimal portion. Using str_replace_all from the stringr package, we can use this:

num <- "1234567890.12345"
str_replace_all(num, "[0-9](?=(?:[0-9]{3})+(?![0-9])(?=\\.))", "\\0,")
[1] "1,234,567,890.12345"

Demo

Unfortunately, a number of Renjin packages are not fully implemented, so until a fix is in place, the code in the question is a decent work around:

commas <- function( n ) {
  s <- sprintf( "%03.0f", n %% 1000 )
  n <- n %/% 1000

  while( n > 0 ) {
    s <- concat( sprintf( "%03.0f", n %% 1000 ), ',', s )
    n <- n %/% 1000
  }

  gsub( '^0*', '', s )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM