HenrikBengtsson / Wishlist-for-R

Features and tweaks to R that I and others would love to see - feel free to add yours!
https://github.com/HenrikBengtsson/Wishlist-for-R/issues
GNU Lesser General Public License v3.0
134 stars 4 forks source link

Native implementation of 'commercial' rounding #121

Open stevecondylios opened 3 years ago

stevecondylios commented 3 years ago

In some countries, the 'default' way of rounding is to always round anything ending with 0.5 up, however, that's not consistent across all parts of the world. Surprisingly (to me, not to everyone), I had been using round() for many years under the assumption it was rounding all numbers ending with 0.5 up, but it doesn't always do so so as to not bias the mean.

Sometimes the user will want a round function that does what is mathematically inferior, but which matches their local norms. round2() has been suggested (and its origins discussed here):

round2 = function(x, n = 0) {
  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
}

# As expected of any round function:
round2(3.5)
[1] 4

# 'commerical' rounding applied as distinct from mathematical rounding
round2(2.5)
[1] 3

# 'commerical' rounding applied beyond the first decimal place too
round2(0.15, 1)
[1] 0.2

If a new function is created, to help enable discovery/investigation on the part of the user, it could be handy to have the new function start with round (so that it auto-completes when using an IDE, and the user is likely to see an alternative function). This could help alert the user that they may need to give some thought to which of the two round* functions they want to use.