Someone must have done this, but I am not seeing an answer. I want to round a vector of numbers to the closest tenth place. I know that I can use the floor function if its a decimal, but that doesn't work for whole numbers

# this works, for decimals floor( 9576.44 ) # I would like this to return 9570 round( 9576 , -1 ) 

2 Answers

This creates a function divides your number by 10 and gives you the whole number portion of the quotient. Then multiples the number by 10 to give you the number you imputed with a floor at the tens place

newfloor <- function(X){ (X %/% 10 ) *10} newfloor(9576) 

So you just always want to clip off the last few digits to round down? How about this function

clip <- function(x, d=1) x - x %% 10**d 

It just does some modulus math to find the last digit of the number and subtract it off.

Then you can do

clip( 9576 , 1 ) # [1] 9570 clip( 9576 , 2 ) # [1] 9500 

Or still using floor, you could just divide and multiple by 10

floor(9576 /10) *10 # [1] 9570 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.