The vec_fmt_number() 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_number() with the default options will create a character vector where the numeric values have two decimal places and NA values will render as "NA". Also, the rendering context will be autodetected unless specified in the output argument (here, it is of the "plain" output type).

vec_fmt_number(num_vals)
[1] "5.20"  "8.65"  "0.00"  "−5.30" "NA"   
#> [1] "5.20" "8.65" "0.00" "-5.30" "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_number(num_vals, sep_mark = ".", dec_mark = ",")
[1] "5,20"  "8,65"  "0,00"  "−5,30" "NA"   
#> [1] "5,20" "8,65" "0,00" "-5,30" "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_number(num_vals, locale = "fr")
[1] "5,20"  "8,65"  "0,00"  "−5,30" "NA"   
#> [1] "5,20" "8,65" "0,00" "-5,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_number(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"

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

vec_fmt_number(num_vals, drop_trailing_zeros = TRUE)
[1] "5.2"  "8.65" "0"    "−5.3" "NA"  
#> [1] "5.2" "8.65" "0" "-5.3" "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_number(num_vals, pattern = "`{x}`")
[1] "`5.20`"  "`8.65`"  "`0.00`"  "`−5.30`" "NA"     
#> [1] "`5.20`" "`8.65`" "`0.00`" "`-5.30`" "NA"