Really basic, but Googling didn't yield an answer. Is there a way to truncate a numeric value without rounding it?
For example:
vars <- c(23.4567, 45.6795, 34.5670)
I want the output to simply lob off the last two significant figures, but not round the output. What I want is:
vars <- c(23.45, 45.67, 34.56)
But the most common ways of doing this end up rounding (round, of course, but also signif:
round(vars, 2)
[1] 23.46 45.68 34.57
signif(vars, digits=4)
[1] 23.46 45.68 34.57
Please point me in the right direction if this has already been addressed here, but couldn't find it specific to R...
You could try with floor()
vars <- floor(vars*100)/100
However, this solution assumes that all values are positive, as floor()
rounds to the next lower integer. If there are negative numbers this approach could yield undesirable results:
> floor(-23.441*100)/100
#[1] -23.45
A more general solution therefore consists in using trunc()
:
vars <- trunc(vars*100)/100
This will remove any digit after the first two decimals, and it also works for negative numbers:
> trunc(-23.441*100)/100
#[1] -23.44
You could use the floor()
function, with a little extra help.
floor(100*vars)/100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With