From R help function: Note that for rounding off a 5, the IEC 60559 standard is expected to be used, ‘go to the even digit’. Therefore round(0.5)
is 0 and round(-1.5)
is -2.
> round(0.5)
[1] 0
> round(1.5)
[1] 2
> round(2.5)
[1] 2
> round(3.5)
[1] 4
> round(4.5)
[1] 4
But I need all values ending with .5 to be rounded down. All other values should be rounded as it they are done by round() function. Example:
round(3.5) = 3
round(8.6) = 9
round(8.1) = 8
round(4.5) = 4
Is there a fast way to do it?
0.5 rounded off to the nearest whole number is 1. Since, the value after decimal is equal to 5, then the number is rounded up to the next whole number. Hence, the whole number of 0.5 will be 1.
ROUND() function rounds the number up or down depends upon the second argument D and number itself(digit after D decimal places >=5 or not). FLOOR() function rounds the number, towards zero, always down.
Both 1.5 and 2.5 are rounded to 2 . 3.5 and 4.5 are rounded to 4 .
What is Rounding Half Up of Numbers? Rounding half up is a rule that is used to round numbers to the nearest integer. When you round a decimal number x to the nearest integer needs some tie breaking rules for x is exactly equal to 0.5. That means if the fractional part of a number is 0.5, then round up the number.
Per Dietrich Epp's comment, you can use the ceiling()
function with an offset to get a fast, vectorized, correct solution:
round_down <- function(x) ceiling(x - 0.5) round_down(seq(-2, 3, by = 0.5)) ## [1] -2 -2 -1 -1 0 0 1 1 2 2 3
I think this is faster and much simpler than many of the other solutions shown here.
As noted by Carl Witthoft, this adds much more bias to your data than simple rounding. Compare:
mean(round_down(seq(-2, 3, by = 0.5))) ## [1] 0.2727273 mean(round(seq(-2, 3, by = 0.5))) ## [1] 0.4545455 mean(seq(-2, 3, by = 0.5)) ## [1] 0.5
What is the application for such a rounding procedure?
Check if the remainder of x %% 1
is equal to .5
and then floor or round the numbers:
x <- seq(1, 3, 0.1) ifelse(x %% 1 == 0.5, floor(x), round(x)) > 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3
I'll join the circus too:
rndflr <- function(x) {
sel <- vapply(x - floor(x), function(y) isTRUE(all.equal(y, 0.5)), FUN.VALUE=logical(1))
x[sel] <- floor(x[sel])
x[!sel] <- round(x[!sel])
x
}
rndflr(c(3.5,8.6,8.1,4.5))
#[1] 3 9 8 4
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