Truncate decimal to specified places

后端 未结 3 412
慢半拍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:23

    Not the most elegant way, but it'll work.

    string_it<-sprintf("%06.9f", old_numbers)
    pos_list<-gregexpr(pattern="\\.", string_it)
    pos<-unlist(lapply(pos_list, '[[', 1)) # This returns a vector with the first 
    #elements
    #you're probably going to have to play around with the pos- numbers here
    new_number<-as.numeric(substring(string_it, pos-1,pos+4)) 
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-16 18:40
    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
    
    0 讨论(0)
提交回复
热议问题