Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round numbers to the closest number with all digits equal to zero but the first digit

Tags:

r

I would round numbers to make all digits zero except one. So for instance, if I have 2341 I would round down to 2000 and up to 3000, for 324 I would round down to 300 and up to 400. Is there a way to round numbers so all digits are zero except the first one? Ideally this should also work with small numbers, so 0.0568 would be rounded down to 0.05 and up to 0.06.

Function like roundUp <- function(x) 10^ceiling(log10(x)) would round up to the closest power of 10 [or lower power if changing ceiling for floor) but in this case 324 would be rounded up to 1000 whereas I would round it up to 400 and down to 300.

like image 725
user3507584 Avatar asked Dec 06 '25 05:12

user3507584


2 Answers

i think the following function does what you want, worked for all examples, also negative values:

special_round <- function(x, type)
{
  z = floor(log10(abs(x)))
  y = 10^z
  res = x/y
  if(type == "up" )
  { 
    res <- ceiling(res)
  }
  if(type == "down")
  {    
    res <- floor(res)
  }
  return(res*y)
}
like image 97
Stefan Avatar answered Dec 08 '25 19:12

Stefan


Following @Michael Lugo answer but making it capable of dealing with negative numbers (like @Stefan Zechner answer) and also adding up and down rounding I did the following.

round_to_zeros = function(x, num.sig.figs = 1, round.down = TRUE){
  initial.x <- as.numeric(x)
  if(x == 0){return(0)}
  if(x < 0){x <- (-1*x)}
  power_of_ten = floor(log(x, 10))

  number_down <- round(floor(x/10^power_of_ten), num.sig.figs-1)*10^power_of_ten
  number_up   <- round( x /10^power_of_ten, num.sig.figs-1)*10^power_of_ten

  if(initial.x < 0){
    if(round.down==TRUE){return(-1*number_up)} else {return(-1*number_down)} }

  if(round.down==TRUE){return(number_down)} else {return(number_up)}
}

This rounds up and down and deals with both negative and positive numbers.

like image 21
user3507584 Avatar answered Dec 08 '25 17:12

user3507584



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!