Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round but .5 should be floored

Tags:

rounding

r

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?

like image 343
Alina Avatar asked Jan 17 '16 23:01

Alina


People also ask

Does a 0.5 round up?

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.

What is the difference between floor and rounding?

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.

Does 2.5 get rounded up or down?

Both 1.5 and 2.5 are rounded to 2 . 3.5 and 4.5 are rounded to 4 .

Do you round up at half?

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.


3 Answers

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?

like image 194
3 revs Avatar answered Sep 30 '22 13:09

3 revs


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 
like image 44
Martin Schmelzer Avatar answered Sep 30 '22 14:09

Martin Schmelzer


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
like image 42
thelatemail Avatar answered Sep 30 '22 12:09

thelatemail