0

A nuance on this question: how to return number of decimal places in R

How can I count the number of digits after the decimal when there are trailing zeros?

Using the function in the accepted answer :

decimalplaces <- function(x) {
  if ((x %% 1) != 0) {
    nchar(strsplit(sub('0+$', '', as.character(x)), ".", fixed=TRUE)[[1]][[2]])
  } else {
    return(0)
  }
}

The goal is to yield a count that includes zeros

With the existing function it ignores trailing zeros, e.g.:

 > decimalplaces(10)
[1] 0
> decimalplaces(10.0)
[1] 0
> decimalplaces(10.00)
[1] 0

Should return 0, 1, and 2 for the examples above.

Minnow
  • 1,733
  • 2
  • 26
  • 52
  • `x %% 1` equals 0 for your examples – CPak Jun 22 '17 at 21:35
  • 1
    I think you have to specify the variable type as character when reading the data from your file / database – Niko Jun 22 '17 at 21:39
  • @Niko I think I have two problems now :) The source is a MySQL database and even with CAST(x, as CHAR) it yields the column field decimals as set in the database, not what is necessarily desired. – Minnow Jun 23 '17 at 01:46
  • I think your SQL database does not store the trailing zeros at all if the field is numeric (https://stackoverflow.com/questions/7028688/trailing-zeroes-not-going-into-database). I think you would have to change the column type in your database to string if you really need the trailing zeros. – Niko Jun 23 '17 at 06:58
  • @Niko Thanks, the zeros are there, it's just that there are too many for some data when using CAST. The column is a decimal (10,3). Different data have zero, one, two, or three decimal places. I'm trying to maintain that precision with calculations. I guess I have a different question to ask... – Minnow Jun 23 '17 at 13:02

0 Answers0