Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf(): number of decimal places as an argument

Tags:

r

Current solution is

dp <- 2
sprintf(paste0("%.", dp, "f"), 0.123)

Hoped-for solution has no paste0() and is similar to

sprintf("%.{%2$d}f", 0.123, 2L)

Except that it works.

like image 548
sindri_baldur Avatar asked Jan 29 '23 03:01

sindri_baldur


2 Answers

You can use a * to insert dp into the format.

dp <- 2
sprintf("%.*f", dp, 0.123)
# [1] "0.12"
like image 176
Rich Scriven Avatar answered Feb 05 '23 04:02

Rich Scriven


Some other possibilities:

# option 1
prettyNum(0.123, digits = dp)

# option 2
formatC(0.123, digits = dp, format = 'f')
like image 42
Jaap Avatar answered Feb 05 '23 04:02

Jaap