0

I am trying to have the line come out straight no matter what number the var is. I tought of putting the last "|" in certain position would help but i have no idea how to do it....

_tipRate = 0.15
_salesTaxRate = 0.085

print("Enter bill amount")
billAmount = round(float(input()), 3)

tipRateAmount = round(_tipRate * billAmount, 3)
salesTaxAmount = round(_salesTaxRate * billAmount, 3)
totalPayAmount = round(billAmount + tipRateAmount + salesTaxAmount, 3)

print(25 * "-")
print("| " + format("Bill", '10s') + " | " + str(billAmount) + " |")
print("| " + format("Sales Tax", '10s') + " | " + str(salesTaxAmount) + " |")
print("| " + format("Gratuity", '10s') + " | " + str(tipRateAmount) + " |")
print("| " + format("Total", '10s') + " | " + str(totalPayAmount) + " |")
print(25 * "-")
JHBonarius
  • 6,889
  • 3
  • 12
  • 28
CForce99
  • 1,094
  • 1
  • 1
  • 17

1 Answers1

2

Using "printf style" formatting strings works well:

_tipRate = 0.15
_salesTaxRate = 0.085
billAmount = 123.45

tipRateAmount = round(_tipRate * billAmount, 3)
salesTaxAmount = round(_salesTaxRate * billAmount, 3)
totalPayAmount = round(billAmount + tipRateAmount + salesTaxAmount, 3)

print(23 * "-")
print("| %-10s | %6.2f |" % ("Bill", billAmount))
print("| %-10s | %6.2f |" % ("Sales Tax", tipRateAmount))
print("| %-10s | %6.2f |" % ("Gratuity", tipRateAmount))
print("| %-10s | %6.2f |" % ("Total", totalPayAmount))
print(23 * "-")

Result:

-----------------------
| Bill       | 123.45 |
| Sales Tax  |  18.52 |
| Gratuity   |  18.52 |
| Total      | 152.46 |
-----------------------

The official docs for this kind of formatting can be found here: https://docs.python.org/3/library/stdtypes.html#old-string-formatting

Python has for a while had second style of formatting that is usually accessed via the <string>.format() method. The docs for that kind of format spec are Here. Here's how that style would be used to get the same results:

print(23 * "-")
print("| {:<10s} | {:6.2f} |".format("Bill", billAmount))
print("| {:<10s} | {:6.2f} |".format("Sales Tax", tipRateAmount))
print("| {:<10s} | {:6.2f} |".format("Gratuity", tipRateAmount))
print("| {:<10s} | {:6.2f} |".format("Total", totalPayAmount))
print(23 * "-")

More recent Python 3 versions (as of 3.6 I think) now have a 3rd style, Formatted String Literal (f-string) formatting. It's much the same as the prior method, but the value being inserted is embedded or referenced directly in the format specifier. Here's the code to again get the same result using this mechanism:

print(23 * "-")
print(f"| {'Bill':<10s} | {billAmount:6.2f} |")
print(f"| {'Sales':<10s} | {tipRateAmount:6.2f} |")
print(f"| {'Gratuity':<10s} | {tipRateAmount:6.2f} |")
print(f"| {'Total':<10s} | {totalPayAmount:6.2f} |")
print(23 * "-")
CryptoFool
  • 15,463
  • 4
  • 16
  • 36