如何在总汽油成本和每英里成本输出中添加 $ 符号?

How can I add a $ sign to Total Gas Cost and Cost Per Mile output?

如何在计算值的前面添加 $。例如,$ 64.6

# Calculate and display total gas cost`enter code here`
total_gas_cost = round(gallons_used * cost_per_gallon, 2)
print("Total Gas Cost:\t", total_gas_cost)

# Calculate and display cost per mile
cost_per_mile = round(cost_per_gallon / miles_per_gallon)
print("Cost Per Mile:\t", cost_per_mile)

试试这个:

print("Total Gas Cost:\t$ ", total_gas_cost)

或者,更好:

print(f"Total Gas Cost:\t$ {total_gas_cost:.2f}")

这是an f-string。变量名后的 .2f 表示“显示 2 个小数位”。这样做通常比对变量本身进行舍入更好,后者可能会导致不精确。

您可以使用 locale 模块:

import locale

locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )

print("Total Gas Cost:", locale.currency(total_gas_cost))