Skip to main content eteppo

Round Numbers To Nth Non-Zero Decimal In R

Published: 2023-08-04
Updated: 2023-08-04
round_nnzd <- function(x, n) {
	assert_that(is.numeric(x), is.numeric(n))
	y <- c()
	i <- 0
	for (xi in x) {
	    i <- i + 1
	    if (xi > -1 & xi < 1) {
                # Round to first significant number
                y[i] <- signif(xi, digits = n)
	    } else {
                # Use regex to split to integer and decimals.
                big_part <- xi %>%
                    as.character() %>%
                    str_remove("\.[0-9]+$") %>%
                    as.integer()
                small_part <- xi - big_part
                if (small_part == 0) {
                    y[i] <- as.numeric(big_part)
                } else {
                    y[i] <- big_part + signif(small_part, digits = n)
                }
	    }
	}
	return(y)
}