目錄
原始文章
在R語言內建的Function中,只有四捨五入(Round),似乎沒有無條件進位或是無條件捨去,這在實務上滿不方便的,所以我們只好自己寫一個。
# 內建四捨五入
round(1254, -2)
> 1300
round(0.1254, 2)
> 0.13
來吧,複製貼上
floor_dec <- function(x, level=1) round(x - 5*10^(-level-1), level)
ceiling_dec <- function(x, level=1) round(x + 5*10^(-level-1), level)
floor_dec(0.1254, 1)
> 0.1
floor_dec(0.1254, 2)
> 0.12
floor_dec(1254, -2)
> 1200
ceiling_dec(1254, -2)
> 1300
這種方法在剛好點5時會出現問題,如0.85要取到小數第二位,程式輸出會是0.84
2020-08-28
08:53:58