The vec_fmt_percent() function

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

num_vals <- c(0.0052, 0.08, 0, -0.535, NA)

Using vec_fmt_percent() with the default options will create a character vector where the resultant percentage values have two decimal places and NA values will render as "NA". The rendering context will be autodetected unless specified in the output argument (here, it is of the "plain" output type).

vec_fmt_percent(num_vals)
[1] "0.52%"   "8.00%"   "0.00%"   "−53.50%" "NA"     
#> [1] "0.52%" "8.00%" "0.00%" "-53.50%" "NA"

We can change the decimal mark to a comma, and we have to be sure to change the digit separator mark from the default comma to something else (a period works here):

vec_fmt_percent(num_vals, sep_mark = ".", dec_mark = ",")
[1] "0,52%"   "8,00%"   "0,00%"   "−53,50%" "NA"     
#> [1] "0,52%" "8,00%" "0,00%" "-53,50%" "NA"

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

vec_fmt_percent(num_vals, locale = "pt")
[1] "0,52%"   "8,00%"   "0,00%"   "−53,50%" "NA"     
#> [1] "0,52%" "8,00%" "0,00%" "-53,50%" "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_percent(num_vals, force_sign = TRUE)
[1] "+0.52%"  "+8.00%"  "0.00%"   "−53.50%" "NA"     
#> [1] "+0.52%" "+8.00%" "0.00%" "-53.50%" "NA"

Those trailing zeros past the decimal mark can be stripped out by using the drop_trailing_zeros option.

vec_fmt_percent(num_vals, drop_trailing_zeros = TRUE)
[1] "0.52%"  "8%"     "0%"     "−53.5%" "NA"    
#> [1] "0.52%" "8%" "0%" "-53.5%" "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_percent(num_vals, pattern = "{x}wt")
[1] "0.52%wt"   "8.00%wt"   "0.00%wt"   "−53.50%wt" "NA"       
#> [1] "0.52%wt" "8.00%wt" "0.00%wt" "-53.50%wt" "NA"