Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate decimal to specified places

Tags:

r

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.

Thanks.

like image 742
Steve Reno Avatar asked Apr 18 '14 16:04

Steve Reno


People also ask

How do I truncate my decimal places?

The TRUNCATE() function truncates a number to the specified number of decimal places.

What does it mean to truncate a decimal?

In simplest terms, truncation means to chop off the decimal portion of a number. This means: Truncating 3.3 returns 3. Truncating 3.8 returns 3.

How do I truncate two decimal places in Excel?

Select the cells that you want to format. On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.


2 Answers

trunc(x*10^4)/10^4

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
like image 99
Robert Krzyzanowski Avatar answered Oct 15 '22 14:10

Robert Krzyzanowski


I used the technics above for a long time. One day I had some issues when I was copying the results to a text file and I solved my problem in this way:

trunc_number_n_decimals <- function(numberToTrunc, nDecimals){
numberToTrunc <- numberToTrunc + (10^-(nDecimals+5))
splitNumber <- strsplit(x=format(numberToTrunc, digits=20, format=f), split="\\.")[[1]]
  decimalPartTrunc <- substr(x=splitNumber[2], start=1, stop=nDecimals)
  truncatedNumber <- as.numeric(paste0(splitNumber[1], ".", decimalPartTrunc))
  return(truncatedNumber)
}
print(trunc_number_n_decimals(9.1762034354551236, 6), digits=14)
[1] 9.176203
print(trunc_number_n_decimals(9.1762034354551236, 7), digits=14)
[1] 9.1762034
print(trunc_number_n_decimals(9.1762034354551236, 8), digits=14)
[1] 9.17620343
print(trunc_number_n_decimals(9.1762034354551236, 9), digits=14)
[1] 9.176203435

This solution is very handy in cases when its necessary to write to a file the number with many decimals, such as 16. Just remember to convert the number to string before writing to the file, using format()

numberToWrite <- format(trunc_number_n_decimals(9.1762034354551236, 9), digits=20)
like image 36
Eduardo Alvim Avatar answered Oct 15 '22 13:10

Eduardo Alvim