您能否帮我修改此代码,将数字写入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 :(得分:1)
在写入csv之前使用round()
函数,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")
答案 1 :(得分:0)
您可以考虑使用format
"{:.2f}".format(24.45679)
给你'24.46'
。