how to return number of decimal places in R

前端 未结 12 1175
走了就别回头了
走了就别回头了 2020-12-01 08:25

I am working in R. I have a series of coordinates in decimal degrees, and I would like to sort these coordinates by how many decimal places these numbers have (i.e. I will w

12条回答
  •  星月不相逢
    2020-12-01 08:52

    I have tested some solutions and I found this one robust to the bugs reported in the others.

    countDecimalPlaces <- function(x) {
      if ((x %% 1) != 0) {
        strs <- strsplit(as.character(format(x, scientific = F)), "\\.")
        n <- nchar(strs[[1]][2])
      } else {
        n <- 0
      }
      return(n) 
    }
    
    # example to prove the function with some values
    xs <- c(1000.0, 100.0, 10.0, 1.0, 0, 0.1, 0.01, 0.001, 0.0001)
    sapply(xs, FUN = countDecimalPlaces)
    

提交回复
热议问题