2017-06-20 80 views
-1

我正在處理具有浮動類型字段的python中的a.CSV文件。任何更好的方式來寫這個小代碼?

必須對此字段進行修改,使其具有至少4個小數點和最多8個精度小數點。

例子:

input: 5.15 
output: 5.1500 

input: -12.129999998 
output: -12.12999999 

什麼我目前做:

#The field to be modifed is present at index 3 in list temp 
dotIndex = temp[3].find('.') + 1 
latLen = len(temp[3])-1 

if (latLen) - (dotIndex) > 8: 
    temp[3] = temp[3][0:dotIndex+4] 
elif (latLen) - (dotIndex) < 4: 
    temp[3] = temp[3][0:latLen] + (4 - (latLen - (dotIndex))) * '0' 

有沒有更好的方式來寫這個代碼以提高性能?

+1

只投'臨時[3]'浮動,然後它的東西,如'打印回寫( '{:8F}'。格式())'。檢查看它有多大,拋光或切割它是太多工作。 –

+1

你打算截斷你的價值觀,還是實際上圍繞它們?你的第二個例子,如果四捨五入適當,應該去13.13000000例如。 – asongtoruin

+0

@ason​​gtoruin我想截斷它們。 – noobcoder

回答

2

這應該工作:

temp[3] = "{:.4f}".format(float(temp[3])) 

考慮您的評論,你想它截斷,在這裏你去一個事實:

n = len(temp[3].split('.')[1]) 
if n < 4: 
    temp[3] = "{:.4f}".format(float(temp[3])) 
elif n > 8: 
    parts = temp[3].split('.') 
    temp[3] = parts[0]+"."+parts[1][:4] 
+0

也應允許最大8點精度。請檢查第二個輸入/輸出示例。 – noobcoder

+0

此外,當n> 8時,我們不能只寫temp [3] =「{:.8f}」。format(float(temp [3])) – noobcoder

+1

格式化浮點數將使其圓整起來 因此, t使用這種方法,因爲你想截斷它 – Trolldejo

1

如果你截斷,而不是四捨五入,你可以使用的東西像這樣:

def truncate_to_eight(val): 
    return '{:.8f}'.format((int(val * 10**8))/(10.0**8)) 

乘以10的冪乘8,取整數部分,然後div 10的權力8獲得你需要的截斷。但是請注意,這將始終返回一個帶有8位小數的值 - 因此5.15變爲5.15000000。

你會說用這個,例如:

rounded = truncate_to_eight(temp[3]) 
相關問題