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:
Is there a way to do this without writing out the regex?
What if I want to maintain the sign? For example, if I wanted to (reverse) truncate -123.456 to -456.
Using the modulo operator (%%) with 1 as the devisor works I guess. It does successfully isolate the numbers following the decimal, but leaves the decimal:
123.456 %% 1
[1] 0.456
However it only works for positive numbers in that the sign is not preserved nor are the proper numbers reported (b/c of modulo operator's functionality):
-123.456 %% 1
[1] 0.544 #not what is wanted
Including abs()
fixes that issue, but doesn't help report sign. Sign could be included by adding:
sign(x) * (abs(x) %% 1)
If we really wanted to report just the digits after the decimal (i.e., excluding the 0 and the decimal), we could do the following (presented in 2 steps for clarity):
x <- -123.456
y <- sign(x) * (abs(x) %% 1)
as.numeric(gsub("0.","",y))
[1] -456 #as desired from part 2 in the OP