Anupam
Anupam

Reputation: 81

Format a number in Indian currency format

Indian currency format uses a comma separator after every 2 digits, except for the last section which is 3 digits. Can one suggest a function in R that can achieve that.

Example:

input 12345678.23 output 1,23,45,678.23
i/p: 4356, o/p: 4,356
i/p: 435, o/p: 435

Upvotes: 5

Views: 3856

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102810

Here might be one option

f <- Vectorize(function(x, digits = 2) {
  r <- ""
  if (grepl(".", x, fixed = TRUE)) {
    r <- c(sub(".*(?=\\.)", "", x, perl = TRUE))
    x <- sub("\\..*", "", x)
  }
  n <- nchar(x)
  r <- paste0(substr(x, n - 2, n), r)
  x <- substr(x, 1, n - 3)
  while (nchar(x)) {
    n <- nchar(x)
    r <- c(substr(x, n - 1, n), r)
    x <- substr(x, 1, n - 2)
  }
  paste0(r, collapse = ",")
})

and you will see

> f(c(12345678.23, 4356, 435, 900425, 1230010.45))
[1] "1,23,45,678.23" "4,356"          "435"            "9,00,425"      
[5] "12,30,010.45"

Upvotes: 1

Allan Cameron
Allan Cameron

Reputation: 174586

I don't know of any native way to do this, but the following function will achieve it for you:

nums <- function(n) {
  dec <- round(n %% 1, 2)
  dec <- ifelse(dec < 0.01, "", substr(dec, 2, 4))
  int <- n %/% 1
  ints <- vapply(int, function(x) {
    x <- as.character(x)
    len <- nchar(x)
    if(len <= 3) return(x)
    rev_x <- paste(rev(unlist(strsplit(x, ""))), collapse = "")
    str   <- paste0(substr(rev_x, 1, 3), ",")
    str2  <- substr(rev_x, 4, 100)
    str2  <- gsub("(\\d{2})", "\\1,", str2)
    rev_x <- paste0(str, str2)
    return(paste(rev(unlist(strsplit(rev_x, ""))), collapse = ""))
  }, character(1))

  return(sub("^,", "", paste0(ints, dec)))
}

You can use it like this:

nums(c(1234.12, 342, 35123251.12))
#> [1] "1,234.12"       "342"            "3,51,23,251.12"

Upvotes: 5

Related Questions