Home > Blockchain >  Format a number in Indian currency format
Format a number in Indian currency format

Time:02-16

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

CodePudding user response:

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"

CodePudding user response:

Here might be one option

f <- Vectorize(function(x, digits = 2) {
  r <- round(x %% 1000L, digits)
  x <- x %/% 1000L
  while (nchar(x) & as.numeric(x) > 0) {
    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))
[1] "1,23,45,678.23" "4,356"          "435"            "9,00,425"  
  • Related