'How do you isolate the digits following a decimal in R?

For example: I have the number 123.456 and want to return 456.

The function trunc() basically isolates (truncates) the numbers before the decimal.

Is there a function to isolate just the digits after the decimal?

Two follow-up questions:

  1. Is there a way to do this without writing out the regex?

  2. What if I want to maintain the sign? For example, if I wanted to (reverse) truncate -123.456 to -456.



Solution 1:[1]

I don't like text processing for these kinds of operations.

The tricky part is converting the fractional number into the integer. Here I use a loop. It's unlikely that many iterations are needed. So, performance is probably not an issue.

fun <- function(x) {
  y <- abs(x) - floor(abs(x))

  n <- 0
  while (abs(y - round(y, n)) > .Machine$double.eps^0.5) {
    n <- n + 1
  }

  sign(x) * y * 10^n
}

fun(123.456)
#[1] 456
fun(-123.456)
#[1] -456

Solution 2:[2]

This is another way to go

> x <- c(123.456, -123.456)
> sign(x) * as.integer(sapply(strsplit(as.character(x), "\\."), "[", 2))
[1]  456 -456

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roland
Solution 2 Jilber Urbina