我想将值从字典写入具有固定小数长度的文件,并使用locale指定的小数分隔符。
我可以做其中任何一个,但我可以将它们组合成“....”。format(x)call。
try:
log_file = open(file_path, "a")
for x in record.values():
log_file.write(str("{:.2f}".format(x)) + ";")
你可以使用locale模块:
locale.str
使用与内置函数str(float)相同的格式格式化浮点数,但要考虑小数点。
import locale
locale.str(round(1.111, 2))
你可以替换'。'由format方法用于replace
函数所需的任何分隔符。例如。如果要使用+
作为分隔符,请使用以下语句:
"{:.2f}".format(5.2).replace('.', '+')