Skip to content
Prev 299383 / 398506 Next

number of decimal places in a number?

Hi Martin,

Ted is spot on about the binary representation.  A very different
approach from his would be to convert to character and use regular
expressions:

## the example numbers in a vector
x <- c(3.14, 3.142, 3.1400, 123456.123456789, 123456789.123456789, pi, sqrt(2))

nchar(gsub("(.*\\.)|([0]*$)", "", as.character(x)))

which for me returns:
[1]  2  3  2  9  6 14 13

an advantage of this approach is that for numbers like
123456789.123456789, although R cannot represent it properly as a
binary number, the character string is totally fine.

nchar(gsub("(.*\\.)|([0]*$)", "", "123456789.123456789"))

returns 9

Essentially the expression looks for anything (the period) zero or
more times (the *) followed by an actual period (the \\.) OR 0
repeated zero or more times at the end of the string, and replaces all
of those with nothing (the "") and then returns the result, the number
of characters of which is counted by nchar()

See ?regex for details

Cheers,

Josh
On Sat, Jul 7, 2012 at 3:04 AM, Ted Harding <Ted.Harding at wlandres.net> wrote: