Format numbers with million (M) and billion (B) suffixes

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.

Leave a Comment