I have a vector of numeric in R:
c(0.9, 0.81)
and I'd like to extract the number of digits for each element in this vector. The command will return, in this case, 1
and 2
since the digits are 9
and 81
. Is there a convenient way to do it? Also, if the result is 1
, how can I expand to two digits? For example, I'd like a returned vector to be
c(0.90, 0.81)
The proof generalizes to compute the number of digits required to represent a number in any base. For example, the number n=1234 written in base 2 requires k = ceil(log2(n+1)) = 11 digits. You can check that the 11-digit binary number 10011010010 equals the decimal value 1234.
To count the digits after the decimal, you can use nchar
sapply(v, nchar) - 2 # -2 for "." and leading 0
# 1 2
x <- c(0.9,0.81,32.52,0);
nchar(sub('^0+','',sub('\\.','',x)));
## [1] 1 2 4 0
This strips the decimal point, then strips all leading zeroes, and finally uses the string length as an indirect means of computing the number of significant digits. It naturally returns zero for a zero input, but you can use an if
expression to explicitly test for that case and return one instead, if you prefer.
As akrun mentioned, for printing with two digits after the decimal:
sprintf('%.2f',x);
## [1] "0.90" "0.81" "32.52" "0.00"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With