The vec_fmt_currency() function

Let’s create a numeric vector for the next few examples:

num_vals <- c(5.2, 8.65, 0, -5.3, NA)

Using vec_fmt_currency() with the default options will create a character vector where the numeric values have been transformed to U.S. Dollars ("USD"). Furthermore, the rendering context will be autodetected unless specified in the output argument (here, it is of the "plain" output type).

vec_fmt_currency(num_vals)
[1] "$5.20"  "$8.65"  "$0.00"  "−$5.30" "NA"    
#> [1] "$5.20" "$8.65" "$0.00" "-$5.30" "NA"

We can supply a currency code to the currency argument. Let’s use British Pounds through currency = "GBP":

vec_fmt_currency(num_vals, currency = "GBP")
[1] "&#163;5.20"  "&#163;8.65"  "&#163;0.00"  "−&#163;5.30" "NA"         
#> [1] "GBP5.20" "GBP8.65" "GBP0.00" "-GBP5.30" "NA"

If we are formatting for a different locale, we could supply the locale ID and let gt handle all locale-specific formatting options:

vec_fmt_currency(num_vals, locale = "fr")
[1] "&#8364;5,20"  "&#8364;8,65"  "&#8364;0,00"  "−&#8364;5,30" "NA"          
#> [1] "EUR5,20" "EUR8,65" "EUR0,00" "-EUR5,30" "NA"

There are many options for formatting values. Perhaps you need to have explicit positive and negative signs? Use force_sign = TRUE for that.

vec_fmt_currency(num_vals, force_sign = TRUE)
[1] "+$5.20" "+$8.65" "$0.00"  "−$5.30" "NA"    
#> [1] "+$5.20" "+$8.65" "$0.00" "-$5.30" "NA"

As a last example, one can wrap the values in a pattern with the pattern argument. Note here that NA values won’t have the pattern applied.

vec_fmt_currency(num_vals, pattern = "`{x}`")
[1] "`$5.20`"  "`$8.65`"  "`$0.00`"  "`−$5.30`" "NA"      
#> [1] "`$5.20`" "`$8.65`" "`$0.00`" "`-$5.30`" "NA"