# Round a number and replace trailing zeros by spaces

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.

• – hplieninger Oct 12 '17 at 6:14

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))

f(c(0.1, 0.1111999, 0.12, 0.1234), n = 4)