Truncate decimal to specified places

Tag: r Author: klaudius Date: 2014-04-02

This seems like it should be a fairly easy problem to solve but I am having some trouble locating an answer.

I have a vector which contains long decimals and I want to truncate it to a specific number of decimals. I do not wish to round it, but rather just remove the values beyond my desired number of decimals.

For example I would like 0.123456789 to return 0.1234 if I desired 4 decimal digits. This is not an issue of printing a specific number of digits but rather returning the original value truncated to a given number.


For a pre-packaged function, try plyr::round_any(.1234567, accuracy=.0001, f=floor)

Best Answer


yields 0.1234 like expected.

More generally,

trunc <- function(x, ..., prec = 0) base::trunc(x * 10^prec, ...) / 10^prec;
print(trunc(0.123456789, prec = 4) # 0.1234
print(trunc(14035, prec = -2), # 14000