简体   繁体   English

如何使字符串格式以固定的精度和语言环境类型的小数点分隔符浮动?

[英]How to make string format float with fixed precision and locale type decimal separator?

I want to write values from dictionary to file with fixed decimal lenght and with use locale specified decimal separator. 我想使用固定的十进制长度和使用区域设置指定的十进制分隔符将值从字典写入文件。

I can do either one of those, but can I compine them both "....".format(x) call. 我可以做任何一个,但是可以将它们都组合为“ ....”。format(x)调用。

try:
   log_file = open(file_path, "a")
   for x in record.values():
       log_file.write(str("{:.2f}".format(x)) + ";")

You can replace the '.' 您可以替换为“。” used by the format method to any separator you want by the replace function. format方法用于replace功能所需要的任何分隔符。 Eg if you want to use a + as a separator, you use the following statement: 例如,如果要使用+作为分隔符,请使用以下语句:

"{:.2f}".format(5.2).replace('.', '+')

You can use locale module: 您可以使用语言环境模块:

locale.str
Formats a floating point number using the same format as the built-in function str(float), but takes the decimal point into account. 使用与内置函数str(float)相同的格式来格式化浮点数,但要考虑到小数点。

import locale
locale.str(round(1.111, 2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM