2015-06-23 94 views
0

您能否幫助我修改此代碼以將數字寫入到cvs文件中的2個小數位?在cvs文件中將字符串寫入2個小數位

outfile = open("numbers.csv", "a") 

outfile.write(str(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')) + "," + str(number_1) + "," + str(number_2) + "," + str(number_3)+ "," + str(number_4) + "," + str(number_5) + "," + str(number_6) + "," + str(number_7) + "," + str(number_8) + "," + str(number_9) +"\n") 

非常感謝。

+0

你的意思是['round()'](https://docs.python.org/3/library/functions.html#round)? – TigerhawkT3

+0

我還建議用一個基本的'list'替換所有'number_1','number_2'等。 – TigerhawkT3

回答

1

在寫入csv之前使用round()函數,圓函數的第二個參數是要舍入爲的小數位數。

示例 -

>>> number_1 = 1.4412324 
>>> number_2 = 1.54988312 
>>> round(number_1,2) 
1.44 
>>> round(number_2,2) 
1.55 

在你的情況 -

outfile = open("numbers.csv", "a") 

outfile.write(str(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')) + "," + str(round(number_1, 2)) + "," + str(round(number_2, 2)) + "," + str(round(number_3, 2))+ "," + str(round(number_4, 2)) + "," + str(round(number_5, 2)) + "," + str(round(number_6, 2)) + "," + str(round(number_7, 2)) + "," + str(round(number_8, 2)) + "," + str(round(number_9, 2)) +"\n") 
0

您可以考慮使用format

"{:.2f}".format(24.45679) 

給你'24.46'