Skip to contents

Format a vector of numbers using format().

Usage

format_number(x, ...)

# S3 method for class 'integer'
format_number(x, bigmark = TRUE, ...)

# S3 method for class 'bignum_biginteger'
format_number(x, bigmark = TRUE, ...)

# S3 method for class 'numeric'
format_number(x, bigmark = TRUE, ...)

# S3 method for class 'bignum_bigfloat'
format_number(x, bigmark = TRUE, ...)

# Default S3 method
format_number(x, ...)

Arguments

x

A vector of numbers to format. The friendlynumber package defines methods for integer, numeric, bignum::biginteger(), and bignum::bigfloat() numbers.

...

Additional arguments passed to or from other methods.

bigmark

[TRUE / FALSE]

Whether the thousands places of formatted numbers should be separated with a comma (e.g. "10,000,000" vs. "10000000"). bigmark is TRUE by default.

Value

A non-NA character vector of the same length as x.

Details

The number of decimal digits shown in the output of format_number() is controlled the friendlynumber.numeric.digits option for numeric vectors and friendlynumber.bigfloat.digits for bignum::bigfloat() vectors.

These options also control the number of decimal digits translated by numeric_friendly() and bigfloat_friendly() respectively. Because of this, format_number() is useful for verifying that the output of these *_friendly() functions is correct.

Examples

format_number(c(1/3, 0, 0.999, NA, NaN, Inf, -Inf))
#> [1] "0.3333333" "0"         "0.999"     "NA"        "NaN"       "Inf"      
#> [7] "-Inf"     
format_number(c(1L, 2L, 1001L))
#> [1] "1"     "2"     "1,001"
format_number(1001L, bigmark = FALSE)
#> [1] "1001"

# Set `friendlynumber.numeric.digits` to control the decimal output
opts <- options()
options(friendlynumber.numeric.digits = 2)
format_number(1234.1234)
#> [1] "1,234.12"
options(opts)

if (requireNamespace("bignum", quietly = TRUE)) {
  format_number(bignum::bigfloat(1234.1234))
  format_number(bignum::biginteger(2000000))

  # Set `friendlynumber.bigfloat.digits` to control the decimal output
  opts <- options()
  options(friendlynumber.bigfloat.digits = 3)
  format_number(bignum::bigfloat(1234.1234))
  options(opts)
}