1

I'm trying to make a cash register, but when I do the tax, I want to have it with two decimal places, instead of something like $3.006743

I tried to do this:

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)

But I get the error. Any help?

user3434967
  • 11
  • 1
  • 2
  • 1
    You can't use bracket notation `[]` on `float`s. You need to make them strings if you want that syntax to be valid. `str(tprice)`. – g.d.d.c Mar 18 '14 at 20:38
  • `tprice` is a float, you cannot index it like that. You just want to round it when printing? – Cory Kramer Mar 18 '14 at 20:39
  • Just use [string formatting](http://docs.python.org/2/library/stdtypes.html#str.format), rather than trying to hard-code rounding or whatever it is you're hoping to do with those subscripts. e.g. `'{0:.2f}'.format(hst)` – Henry Keiter Mar 18 '14 at 20:40

2 Answers2

2

You can use string formatting:

>>> '{:.2f}'.format(3.123456) 
'3.12'
>>> '$ {:.2f}'.format(12.999)
'$ 13.00'
>>> '{:.2f}'.format(.029)
'0.03'
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
1

If you are using this for currencies I would also recommend looking at python limiting floats to two decimal points, because rounding floats will cause your calculations to be incorrect. Many people store cents (in an integer) and divide by 100, or use python's Decimal type.

Community
  • 1
  • 1
Aaron
  • 2,341
  • 21
  • 27