Truncate decimal to specified places

后端 未结 3 416
慢半拍i
慢半拍i 2020-12-16 18:11

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

3条回答
  •  死守一世寂寞
    2020-12-16 18:25

    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)
    

提交回复
热议问题