1

I am trying to round the following numbers to 3 significant figures. The output is not always what I expected. signif(14.65, digits = 3) expected output: 14.7; actual output: 14.6 signif(14.45, digits = 3) expected output: 14.5; actual output: 14.4

When the number is 5, is it always round down instead of up?

Snakelemma
  • 11
  • 1

3 Answers3

0

According to documentation :

signif rounds the values in its first argument to the specified number of significant digits. Hence, for numeric x, signif(x, dig) is the same as round(x, dig - ceiling(log10(abs(x)))).

Clemsang
  • 4,161
  • 2
  • 23
  • 38
  • `round` and `signif` have the same expected behavior. It rounds to the nearest even digit. – harre May 31 '22 at 11:37
  • Yes you are right. Keep in mind that `signif(14.65, digits = 3)` is `14.6` and `round(14.65, digits = 1)` is `14.7`. – Clemsang May 31 '22 at 11:43
  • Basically there are two forms of rounding: 1. `commercial rounding`: at .5 we round away from 0 -> in positive numbers to higher numbers. 2. `mathematical rounding`: round half to even -> always round to the nearest even number. `signif` usues mathematical rounding. – TarJae May 31 '22 at 16:17
0

It is the the intended behavior to round to the nearest even digit, which explains the OP behavior. However, it can be OS dependent.

Note that for rounding off a 5, the IEC 60559 standard (see also ‘IEEE 754’)
is expected to be used, ‘go to the even digit’. Therefore round(0.5) is 0
and round(-1.5) is -2. However, this is dependent on OS services and on
representation error (since e.g. 0.15 is not represented exactly, the rounding
rule applies to the represented number and not to the printed number, and so
round(0.15, 1) could be either 0.1 or 0.2).

[Package base version 4.1.3]

harre
  • 962
  • 1
  • 5
  • 17
-1

Code:

round2 = function(x, n) {
  posneg = sign(x)
  z = abs(x)*10^n
  z = z + 0.5 + sqrt(.Machine$double.eps)
  z = trunc(z)
  z = z/10^n
  z*posneg
}
x = c(14.65, 14.45, 14.64, 14.43)
round2(x, 1)

Output:

> round2(x, 1)
[1] 14.7 14.5 14.6 14.4
Rajan
  • 121
  • 8
  • 3
    Please put a reference to the posts, it is not ideal to just copy-paste: https://stackoverflow.com/questions/12688717/round-up-from-5?rq=1 or from http://andrewlandgraf.com/2012/06/15/rounding-in-r/ – harre May 31 '22 at 11:33