1
\$\begingroup\$

Goal

From a number x, I would like a string of the rounded value at n decimals and replace each trailing zeros by a space.

Examples

Let n = 4

f(0.1, n=4)
[1] "0.1   " # 3 whitespace
f(0.1111999, n=4)
[1] "0.1112" # 0 whitespace
f(0.12, n=4)
[1] "0.12  " # 2 whitespace
f(0.1234, n=4)
[1] "0.1234" # 0 whitespace

Current solution

f <- function(x,n)
{
    s = sprintf(paste0("%.",n,"f"), x)
    for (i in 1:n)
    {
        s = gsub(
            paste0("0", paste0(rep("\\s",i-1),collapse=""),"$"),
            paste0(rep(" ",i), collapse=""),
            s
        )       
    }
    return(s)
}

It works fine but it is a little cumbersome. I suspect a better regex solution.

\$\endgroup\$
4
\$\begingroup\$

Apparently, printf already has a feature for padding data to a specific length, see for example https://stackoverflow.com/q/34346389/1201032. So you can do:

f <- function(x, n) {
  rounded_x <- as.character(round(x, n))
  num_lead_chars <- nchar(sub("[.].*", ".", rounded_x))
  sprintf("%-*s", n + num_lead_chars, rounded_x)
}

The function is vectorized for both inputs:

f(c(0.1, 0.1111999, 0.12, 0.1234), n = 4)
# [1] "0.1   " "0.1112" "0.12  " "0.1234"
f(0.1, n = 1:4)
# [1] "0.1"    "0.1 "   "0.1  "  "0.1   "
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.