emehex - 3 months ago 18
R Question

# Formatting large currency or dollar values to millions/billions

I need a simple function or package that will format:

``````1 6,000,000
2 75,000,400
3 743,450,000
4 340,000
5 4,300,000
``````

To:

``````1 6.0 M
2 75.0 M
3 743.5 M
4 0.3 M
5 4.3 M
``````

Or otherwise make large values (millions, billions) more legible for printing out in a table.

If you begin with this numeric vector `x`

``````x <- c(6e+06, 75000400, 743450000, 340000, 4300000)
``````

you could do the following.

``````paste(format(round(x / 1e6, 1), trim = TRUE), "M")
# [1] "6.0 M"   "75.0 M"  "743.5 M" "0.3 M"   "4.3 M"
``````

And if you're not concerned about trailing zeros, just remove the `format()` call.

``````paste(round(x / 1e6, 1), "M")
# [1] "6 M"     "75 M"    "743.5 M" "0.3 M"   "4.3 M"
``````

Alternatively, you could assign an S3 class with print method and keep `y` as numeric underneath. Here I use `paste0()` to make the result a bit more legible.

``````print.million <- function(x, quote = FALSE, ...) {
x <- paste0(round(x / 1e6, 1), "M")
NextMethod(x, quote = quote, ...)
}
## assign the 'million' class to 'x'
class(x) <- "million"
x
# [1] 6M     75M    743.5M 0.3M   4.3M
x[]
# [1]   6000000  75000400 743450000    340000   4300000
``````

You could do the same for billions and trillions as well. For information on how to put this into a data frame, see this answer, as you'll need both a `format()` and an `as.data.frame()` method.