formatN: Compact Numeric Formatting

View source: R/misc-goodies.R

formatNR Documentation

Compact Numeric Formatting

Description

A simple utility getting more compact numeric representations, currently for “exponential” aka “scientific” format.

Usage

formatN(x, digits = 1L, sci = c(-1L, -2L))

Arguments

x

numeric or complex vector of numbers.

digits

positive integer number of digits to use.

sci

one or two small integers specifying format.default's scientific argument (see options("scipen")) for abs(x) < 1 and \ge 1. Note that the default (-2. -1) seems optimal; this argument exists mostly to explore possibilities and to prove optimality of its default.

Value

a character vector of the same length as x.

Author(s)

Martin Maechler

See Also

format, sprintf, formatC, are or can be used similarly.

Examples

(x <- c(outer(c(1,pi), 10^(-10:11))))
sum(nchar(f1 <- format(x, digits=1)))        # 220
sum(nchar(f2 <- sapply(x, format, digits=1)))# 194
sum(nchar(ff1<- formatN(x, sci=-1L)))        # 152
sum(nchar(ff2<- formatN(x, sci=-2L)))        # 150
sum(nchar(ff <- formatN(x)))                 # 150 .. the best
sum(nchar(ff3<- formatN(x, sci=-3L)))        # 152
noquote(rbind(f1, f2, ff1, ff, ff2, ff3))
## the best is ff (where sci differs for neg.exp and pos.ex) - for this example

## the "extreme" formatting still keeps "95%" of numerical info :
stopifnot(all.equal(x, as.numeric(formatN(x)), tolerance = 0.05))

sfsmisc documentation built on Nov. 21, 2025, 9:06 a.m.