Calculate the number of digits in a number vector in R

I have a number vector in R:

c(0.9, 0.81) 

and I would 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 numbers 9 and 81 . Is there any convenient way to do this? Also, if the result is 1 , how can I expand up to two digits? For example, I would like the returned vector to be

  c(0.90, 0.81) 
+5
source share
2 answers
 x <- c(0.9,0.81,32.52,0); nchar(sub('^0+','',sub('\\.','',x))); ## [1] 1 2 4 0 

This breaks the decimal point, then breaks all the leading zeros, and finally uses the string length as an indirect means of calculating the number of significant digits. It naturally returns zero for null input, but you can use the if expression to explicitly test for this case and, if you want, return it instead.

As mentioned in akrun, for printing with two digits after a decimal number:

 sprintf('%.2f',x); ## [1] "0.90" "0.81" "32.52" "0.00" 
+3
source

To count the digits after the decimal place, you can use nchar

 sapply(v, nchar) - 2 # -2 for "." and leading 0 # 1 2 
+6
source

All Articles