Here round() behaves as expected:
round(3.5)
[1] 4
However this was surprising to me:
round(2.5)
[1] 2
In times when we want everything ending in .5 to be rounded up, what's best practice in R to achieve that?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With