Add a discount and sales tax to a single-item purchase using integer math.
You start with:
val item = "Coffee Mug"
val price = 12
val quantity = 3
val taxRate = 8
val discount = 5
Build:
Subtotal: $36 Discount: $5 Tax: $2 Total: $33
Rules:
subtotal = price * quantity.afterDiscount = subtotal - discount(the discount is a flat amount taken off before tax).tax = afterDiscount * taxRate / 100(integer division, so the result is rounded down). The tax is charged on the discounted amount.total = afterDiscount + tax.- Build four lines (
Subtotal,Discount,Tax,Total) and join them with a newline"\n"into one stringresult, then print it withprintln(result).
Compute the four numbers (
subtotal, afterDiscount, tax, total) before formatting.
In Kotlin
"Total: $" + total converts the number to text for you.
Kotlin's
Int / Int truncates, so afterDiscount * taxRate / 100 already rounds down.
val item = "Coffee Mug"
val price = 12
val quantity = 3
val taxRate = 8
val discount = 5
val subtotal = price * quantity
val afterDiscount = subtotal - discount
val tax = afterDiscount * taxRate / 100
val total = afterDiscount + tax
val line1 = "Subtotal: $" + subtotal
val line2 = "Discount: $" + discount
val line3 = "Tax: $" + tax
val line4 = "Total: $" + total
val result = line1 + "\n" + line2 + "\n" + line3 + "\n" + line4
println(result)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
