Skip to contents

Round the numeric elements of an atomic vector and return a character vector. Elements that do not represent a single number are left unchanged.

Usage

round2(x, digits = 3L)

Arguments

x

(atomic vector)
The vector whose numeric elements should be rounded.

digits

(scalar whole number: 3L)
The number of decimal places for rounded numbers. Must be finite.

Value

A character vector the same length as x.

Details

Each element is coerced to character, then parsed with base::as.numeric(). Elements that parse to a finite number or to Inf/-Inf are rounded to digits decimal places. All other elements pass through unchanged, including text such as "$99.99", "NaN", and NA.

A nonzero value that rounds to zero loses all magnitude information. Such values are shown in compact scientific notation (for example "1.0e-04") instead of "0". Exact zero is returned as "0".

Logical input is rendered as "TRUE"/"FALSE" rather than 0/1. Names on x are preserved.

Examples

#----------------------------------------------------------------------------
# round2() example
#----------------------------------------------------------------------------
library(bkbase)

round2(c("hello", "0.0001", "1.23456", "hello 1.23456"))
#> [1] "hello"         "1.0e-04"       "1.235"         "hello 1.23456"