Skip to contents

Converts a numeric vector into strings rounded to a significant-figure-like number of digits. Scientific notation is avoided, and additional significant figures may be displayed for large numbers: with 2 significant figures requested, 123 is displayed as "123" rather than "120" or "1.2e2".

Usage

style_sigfig(
  x,
  digits = 2,
  scale = 1,
  big.mark = ifelse(decimal.mark == ",", " ", ","),
  decimal.mark = getOption("OutDec"),
  prefix = "",
  suffix = "",
  na = NA_character_,
  ...
)

Arguments

x

(numeric)
Numeric vector.

digits

(integer)
Number of significant figures.

scale

(scalar numeric)
Values are multiplied by scale before rounding, e.g. scale = 100 to show a proportion as a percentage.

big.mark

(string)
Character used between every three digits to the left of the decimal mark.

decimal.mark

(string)
Character used as the decimal mark.

prefix, suffix

(string)
Text added before and after each formatted value.

na

(string)
Replacement for missing values.

...

Not used. Accepted so that formatting functions can be called interchangeably.

Value

A character vector the same length as x.

Details

  • Scientific notation output is avoided.

  • If 2 significant figures are requested, the number is rounded to no more than 2 decimal places: a number is rounded to 2 decimal places when abs(x) < 1, to 1 decimal place when abs(x) >= 1 & abs(x) < 10, and to the nearest integer when abs(x) >= 10.

  • Additional significant figures may be displayed for large numbers.

Examples

c(0.123, 0.9, 1.1234, 12.345, -0.123, -0.9, -1.1234, -132.345, NA, -0.001) |>
  style_sigfig()
#>  [1] "0.12"  "0.90"  "1.1"   "12"    "-0.12" "-0.90" "-1.1"  "-132"  NA     
#> [10] "0.00" 
c(0.9949, 0.995, 1.005, 12.345) |>
  style_sigfig(digits = 3)
#> [1] "0.995" "0.995" "1.01"  "12.3"