Reputation: 2511
As per the title, I need a string format where
sprintf(xxx,5) prints "5"
sprintf(xxx,5.1) prints "5.1"
sprintf(xxx,15.1234) prints "15.12"
That is: no leading zeros, no trailing zeros, maximum of 2 decimals.
Is it possible? if not with sprintf, some other way?
The use case is to report degrees of freedom which are generally whole numbers, but when corrected, may result in decimals - for which case only I want to add two decimals).
Upvotes: 1
Views: 1507
Reputation: 132706
Maybe formatC
is easier for this:
formatC(c(5, 5.1, 5.1234), digits = 2, format = "f", drop0trailing = TRUE)
#[1] "5" "5.1" "5.12"
Upvotes: 2
Reputation: 1327
A solution based on sprintf
as suggested:
sprintf("%.4g", 5)
#[1] "5"
sprintf("%.4g", 5.1)
#[1] "5.1"
sprintf("%.4g", 15.1234)
#[1] "15.12"
Verbose information to sprintf
can be found e.g. here: http://www.cplusplus.com/reference/cstdio/printf/
which says:
g | Use the shortest representation: %e or %f
and
.number | ... For g and G specifiers: This is the maximum number of significant digits to be printed.
Upvotes: 0