【问题标题】:Formatting a list of floats to 2 Decimal Points将浮点数列表格式化为 2 个小数点
【发布时间】:2015-11-02 15:33:41
【问题描述】:

我正在尝试通过文本搜索以查找 Money EG £12.30 获取数字然后将它们相加。我已经设法达到我有一个浮点列表但我似乎无法将它们变为 2小数点。但是,就像在下面的代码中一样,如果我在列表中指定一个元素,例如 [0],那么它将将该元素格式化为 2 个小数点。

所以我的问题是: 如何将整个列表格式化为小数点后 2 位,记住我不知道列表会有多长。

import re

num_regex = re.compile(r'\d\d.\d\d')
file_name = input("Enter File Name to open: ")

text_file = open(file_name, 'r')
search_text = text_file.read()
search = num_regex.findall(search_text)
print("Numbers found:", search,)
new_search =[]
for item in search:
    new_search.append(float(item))
new_search[0] = "%.2f" % new_search[0]
print(new_search[0])

【问题讨论】:

  • 使用decimal 模块而不是float()
  • 我已经开始阅读它,但它要复杂得多。我对编程非常陌生,而且由于行话,很难阅读这些文本并从中获取任何有用的东西!
  • 货币值是fixed-point,不是浮点数。对货币使用浮点运算并不明智,因为计算机表示浮点值的方式会导致意外舍入。
  • 太困惑了,我将把它作为 12.3 做些什么,或者感谢一堆:)
  • 对于结果列表中的项目:(Decimal(item).quantize(Decimal('.02'))) NewResultList.append(item) 对吗?

标签: python regex python-3.x floating-point decimal


【解决方案1】:

如何将整个列表格式化为小数点后 2 位,我不知道该列表会有多长。

您使用for 循环,遍历您的数字列表,可能在列表理解中。考虑以下每一个:

formatted_list = []
for item in new_search:
    formatted_list.append("%.2f"%item)
print("Formatted List:", formatted_list)

或者,等效地:

formatted_list = ["%.2f"%item for item in new_search]
print("Formatted List:", formatted_list)

这是您的整个程序,使用列表推导:

import re

num_regex = re.compile(r'\d\d.\d\d')
file_name = input("Enter File Name to open: ")

text_file = open(file_name, 'r')
search_text = text_file.read()
search = num_regex.findall(search_text)
print("Numbers found:", search,)
new_search =[float(item) for item in search]
print("Numbers found:", new_search,)
formatted_search =["%.2f"%item for item in new_search]
print("Numbers found:", formatted_search,)

【讨论】:

【解决方案2】:

在将变量附加到列表之前对其进行格式化

item_price = []
price = float(input('What is the price of the item? '))
    fprice = '{:.2f}'.format(price)
    item_price.append(fprice)

【讨论】:

    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2013-08-11
    • 2016-09-09
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    相关资源
    最近更新 更多