2016-09-23 75 views
0

如何在R中削減商的小數?我正在計算數百萬個值,並將它們隨時寫入文件中。爲了節省一些空間,我不想超過五位小數,也省略尾隨零。R中的最大小數位數

我試圖

options(digits=5) 

我只讀是一個建議,R和不工作不幹好。並且

format(x, nsmall = 5) 

僅確定最小小數位數。和

sprintf("%.5f", x) 

會給我五位小數。

回答

2

如何只用

round(x,5) 
x=1.23456777 
round(x,5) 
#[1] 1.23457 
x=1.230000 
#round(x,5) 
[1] 1.23 

如果你不想四捨五入試試這個:如果您從預先地改變數字選項避免

as.integer(x*10^5)/10^5 

x=1.234567777 
as.integer(x*10^5)/10^5 
#[1] 1.23456 
x=1.230000 
as.integer(x*10^5)/10^5 
#[1] 1.23 
+1

感謝您的建議,但我想有必要時的正好五個小數精度。圓的方法會有所不同,第一個x的輸出不會是1.23457,而是1.2346 – Wipster

+1

@Wipster你在尋找'signif'嗎? – Roland

+0

好的,根據您的要求更新。我想你想1.23456爲1.234567777對不對? –

1

循環函數工作得很好。

默認選項

運行:

> round(x = 1.23456777, digits = 5) 
[1] 1.23457 

運行與更改的選項:

> options(digits=5) 
> round(x = 1.23456777, digits = 5) 
[1] 1.2346 
+0

P.S .:數字的默認值是7('getOption(「digits」)') – 2016-09-23 10:15:53