python - “float”对象不可下标

标签 python typeerror

我正在尝试制作一个收银机,但是当我报税时,我希望它具有两位小数,而不是像 $3.006743 这样的东西

我尝试这样做:

elif item == 'done':
    os.system('cls')
    tprice = sprice * 1.13
    hst = tprice - sprice
    if tprice >= 1:
        tprice = tprice[0:5]
    elif tprice >= 10:
        tprice = tprice[0:6]
    elif tprice >= 100:
        tprice = tprice[0:7]
    if hst >= 1:
        hst = hst[0:5]
    elif hst >= 10:
        hst = hst[0:6]
    elif hst >= 100:
        hst = hst[0:7]
    print(receipt)

但我收到错误。有什么帮助吗?

最佳答案

您可以使用string formatting:

>>> '{:.2f}'.format(3.123456) 
'3.12'
>>> '$ {:.2f}'.format(12.999)
'$ 13.00'
>>> '{:.2f}'.format(.029)
'0.03'

关于python - “float”对象不可下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22490478/

相关文章:

javascript - 类型错误:为空

python - 使用 groupby+apply 对每个组进行聚类 - 性能问题

python - 如何将 'using' DB 传递给 django 连接对象

Python:如何在请求中使用 Chrome cookie

Python OpenAI API 类型错误

haskell - 为什么会收到类型错误?

java - ArrayList<> 无法解析为类型

javascript - 如何通过 jinja[Flask] 访问外部 javascript 文件?

python - 了解 Keras LSTM ( lstm_text_generation.py ) - RAM 内存问题

Python 正在工作 - 没有做任何更改 - 将不再工作。可能发生了什么?