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