Skip to main content

Format Numbers the Same Way as SAS

Source: R/sas_round.R

Description

sas_format() formats numbers with a fixed number of decimal places so that the printed values match the SAS w.d format (e.g., 8.2).

Usage

sas_format(x, digits = 0, ...)

Arguments

Arguments Description
x A numeric vector.
digits A single whole number between 0 and 15 for the number of decimal places to show. As in round(), and unlike format(), this is the number of decimal places and not the number of significant digits.
… Formatting options, as in format(): width, justify, trim, big.mark, big.interval, small.mark, small.interval, decimal.mark, and scientific. Scientific notation is not used unless scientific = TRUE is passed, in which case the rounded values are formatted with format(digits = 15).

Details

SAS formats do not round with the ROUND() function, so sas_format() does not use sas_round(). With the default DECIMALCONV=COMPATIBLE system option, SAS:

• Rounds x * 10^digits half away from zero. Values within a relative 1e-16 of a halfway point (about one unit in the last place) are treated as halfway, so 2.675 (stored as slightly less than 2.675) is shown as 2.68 with two decimal places.

• Shows at most 15 significant digits. When more digits are needed, the number is first rounded to 15 significant digits and zeros are shown after them (sas_format(123456789.123456, 10) is "123456789.1234560000").

• Keeps the sign of negative numbers that round to zero, so -0.4 is shown as -0 and -0.001 as -0.00 with two decimal places.

• Treats subnormal numbers (smaller than .Machine$double.xmin) as zero.

The tolerance is much smaller than the one used by ROUND(): 0.4999999999999982 is shown as 0, but sas_round(0.4999999999999982) is 1. So sas_format(x, digits) can differ from format(sas_round(x, digits), nsmall = digits).

These results were compared with about 100,000 results of the SAS 32.d formats (SAS Viya, V.04.00M0P060826), including every value with up to four decimal places in a range around zero. They are identical except within a few units in the last place of a halfway point, where SAS’s tolerance varies from value to value, and when 15 or more digits are shown, where SAS’s digits are not consistent (1/3 is shown as 0.333333333333330 with 15 decimal places).

With DECIMALCONV=STDIEEE, SAS formats the exact binary value instead (2.675 is shown as 2.67); sas_format() does not replicate that.

Value

A character vector the same length as x. As with format(), the values share a common width and names are kept.

Examples

format(round(1.005, 2), nsmall = 2)
[1] "1.00"
sas_format(1.005, digits = 2)
[1] "1.01"
sas_format(c(0.5, 1.5, 2.5, -2.5))
[1] " 1" " 2" " 3" "-3"
[1] "-0"
sas_format(1234567.891, digits = 2, big.mark = ",")
[1] "1,234,567.89"

See Also

sas_round()