TNT TNT - 16 days ago 10
R Question

R sprintf maximum two decimals but no leading zeros

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

Answer

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"
Comments