user26480
user26480

Reputation: 387

show just a number after the decimal point for a number in R

I can't find the way to show just 2 numbers after the decimal point for a number in R, I don't want round the number, I just want to display the number two as they are.

eg:

1.29964 I want to display: 1.29

Upvotes: 0

Views: 1088

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

Happy fun time gsub answer. You could put together a function with a pasted regular expression.

adjust <- function(x, y) {
    p <- paste0("([0-9]+[.])([0-9]{", y, "}).*")
    Vectorize(gsub, USE.NAMES = FALSE)(p, "\\1\\2", x)
}
adjust(1.29964, 1:5)
# [1] "1.2"     "1.29"    "1.299"   "1.2996"  "1.29964"
lapply(0:5, function(x) as.numeric(adjust(1.29964, x)))
#[[1]]
#[1] 1
#
#[[2]]
#[1] 1.2
#
#[[3]]
#[1] 1.29
#
#[[4]]
#[1] 1.299
#
#[[5]]
#[1] 1.2996
#
#[[6]]
#[1] 1.29964

Upvotes: 2

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162321

trunc() does almost, but not quite, what you are wanting. To generalize it a bit, write a function like this:

f <- function(x, d) {
   trunc(x*10^d)/10^d
}

set.seed(1)
x <- rnorm(5)
x
# [1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078
f(x,2)
# [1] -0.62  0.18 -0.83  1.59  0.32
f(x,4)
# [1] -0.6264  0.1836 -0.8356  1.5952  0.3295

Upvotes: 6

Related Questions