Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commercial rounding in R - i.e. always round up from .5?

Tags:

r

Here round() behaves as expected:

round(3.5)
[1] 4

However this was surprising to me:

round(2.5)
[1] 2

Question

In times when we want everything ending in .5 to be rounded up, what's best practice in R to achieve that?

Note

Ideally the solution should also cater for rounding beyond the first decimal place e.g. the following should return 0.2:

round(0.15, 1)
[1] 0.1
like image 434
stevec Avatar asked Nov 01 '25 15:11

stevec


1 Answers

After googling for 'commercial rounding in r', this answer comes up, which can be adapted to have a default value of 0 decimal places like so:

round2 = function(x, decimal_places = 0) {
  posneg = sign(x)
  z = abs(x)*10^decimal_places
  z = z + 0.5 + sqrt(.Machine$double.eps)
  z = trunc(z)
  z = z/10^decimal_places
  z*posneg
}

Examples:

round2(3.5)
[1] 4

round2(2.5)
[1] 3

round2(0.15, decimal_places = 1)
[1] 0.2
like image 155
stevec Avatar answered Nov 03 '25 06:11

stevec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!