Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up from .5

Tags:

rounding

r

r-faq

Yes I know why we always round to the nearest even number if we are in the exact middle (i.e. 2.5 becomes 2) of two numbers. But when I want to evaluate data for some people they don't want this behaviour. What is the simplest method to get this:

x <- seq(0.5,9.5,by=1) round(x) 

to be 1,2,3,...,10 and not 0,2,2,4,4,...,10.

Edit: To clearify: 1.4999 should be 1 after rounding. (I thought this would be obvious)

like image 237
jakob-r Avatar asked Oct 02 '12 10:10

jakob-r


People also ask

Why do we round .5 up?

If there is a non-zero digit, then we round up, because the number is greater than 0.15. Either way we round up, which means that we don't actually need to bother looking at any places to the right of the hundredths place to determine our action.

Does .5 or higher round up?

If that first digit to be dropped is more than 5 (that is, 6, 7, 8 or 9), increase by 1 the number to be rounded, that is, the preceeding figure (to the digit being dropped). If that first digit to be dropped is 5, round the digit that is to rounded off so that it will be even.

What does round to 0.5 mean?

05. So that if its 9.3 it would round up to 9.5 but if its 9.1 it would round down to 9.0. See my example screenshot. The nearest . 05 for 1.1 would be 1.0 and for 9.9 it would 10.


2 Answers

This is not my own function, and unfortunately, I can't find where I got it at the moment (originally found as an anonymous comment at the Statistically Significant blog), but it should help with what you need.

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

x is the object you want to round, and n is the number of digits you are rounding to.

An Example

x = c(1.85, 1.54, 1.65, 1.85, 1.84) round(x, 1) # [1] 1.8 1.5 1.6 1.8 1.8 round2(x, 1) # [1] 1.9 1.5 1.7 1.9 1.8 

(Thanks @Gregor for the addition of + sqrt(.Machine$double.eps).)

like image 185
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 19 '22 13:09

A5C1D2H2I1M1N2O1R2T1


If you want something that behaves exactly like round except for those xxx.5 values, try this:

x <- seq(0, 1, 0.1) x # [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 floor(0.5 + x) # [1] 0 0 0 0 0 1 1 1 1 1 1 
like image 33
flodel Avatar answered Sep 20 '22 13:09

flodel