以印度货币格式格式化数字

Format a number in Indian currency format

印度货币格式在每 2 位数字后使用逗号分隔符,但最后一节是 3 位数字。有人可以建议 R 中的一个函数来实现这一点吗?

示例:

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

我不知道有什么本机方法可以做到这一点,但以下函数将为您实现:

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

你可以这样使用它:

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

这里可能有一个选项

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 = ",")
})

你会看到

> 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"