从分到美元的数字格式化

2 投票
4 回答
8160 浏览
提问于 2025-04-17 19:02

我正在尝试使用Python 2.7的字符串格式化功能,输出十个苹果的价格,单位价格是以美分为单位的。

我希望total_apple_cost的值是"10.00",但它却变成了"1.001.001.001.001.001.001.001.001.001.00"

我已经包含了其他变量的测试,以证明它们的结果都是正确的:

# define apple cost in cents
apple_cost_in_cents = 100
# define format string
cents_to_dollars_format_string = '{:,.2f}'
# convert 100 to 1.00
apple_cost_in_dollars = cents_to_dollars_format_string.format(apple_cost_in_cents / 100.)
# assign value of 'apple_cost_in_dollars' to 'apple_cost'
apple_cost = apple_cost_in_dollars
# calculate the total apple cost
total_apple_cost = 10 * apple_cost

# print out the total cost
print 'total apple cost: ' + str(total_apple_cost) + '\n'

#testing
print 'cost in cents: ' + str(apple_cost_in_cents) + '\n'
print 'cost in dollars: ' + str(apple_cost_in_dollars) + '\n'
print 'apple cost: ' + str(apple_cost) + '\n' 

解决方案:

感谢下面的回答,它们都指出了变量'apple_cost_in_dollars'是一个字符串。

我的解决方案是把它改成浮点数,其他代码基本保持不变:

apple_cost_in_cents = 100
cents_to_dollars_format_string = '{:,.2f}'
apple_cost_in_dollars = float(cents_to_dollars_format_string.format(apple_cost_in_cents / 100.))
apple_cost = apple_cost_in_dollars
total_apple_cost = 10 * apple_cost

print 'cost in cents: ' + str(apple_cost_in_cents) + '\n'

print 'cost in dollars: $''{:,.2f}'.format(apple_cost_in_dollars) + '\n'

print 'apple cost: $''{:,.2f}'.format(apple_cost) + '\n'

print 'total apple cost: $''{:,.2f}'.format(total_apple_cost) + '\n'

4 个回答

2

apple_cost 是一个字符串,你把它乘以 10,这样做的结果就是把这个字符串重复 10 次。在把它格式化成字符串之前,先把它转换成美元。

>>> apple_cost_in_cents = 100
>>> cents_to_dollars_format_string = '{:,.2f}'
>>> total_apple_cost_in_dollars_as_string = cents_to_dollars_format_string.format(10*apple_cost_in_cents/100.0)
>>> total_apple_cost_in_dollars_as_string
'10.00'

如果你想更深入地了解货币格式化,可以看看 locale 模块,特别是 locale.currency 这个函数。

2

这段代码是用来处理某些数据的。它可能涉及到一些循环、条件判断或者数据存储的操作。具体来说,代码块中的内容会按照一定的逻辑来执行,可能会从一个地方获取数据,然后进行处理,最后把结果输出或者存储起来。

如果你是编程新手,可以把这段代码想象成一个食谱。食谱里会告诉你需要哪些材料(数据),然后一步一步教你怎么做(处理),最后得到一道美味的菜(结果)。

总之,这段代码的目的是为了让计算机按照我们设定的步骤来完成某项任务。

>>> import locale
>>> apple_cost_in_cents = 100
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.UTF-8'
>>> locale.currency(apple_cost_in_cents * 10 / 100)
'$10.00'
4

这是因为 apple_cost_in_dollars 是一个字符串,下面有示例代码。

In [9]: cost = '1'

In [10]: cost * 10
Out[10]: '1111111111'

In [11]: cost = int('1')

In [12]: cost * 10
Out[12]: 10

撰写回答