CodeBlanks Logo Icon CodeBlanks

Apply discount

Learn percentage discount logic.

Percentage discount

A percentage discount is applied by multiplying the amount by (1 - percent / 100). For example, a 20% discount on 100 gives 80: 100 * (1 - 20/100) = 80.

function applyDiscount(amount: number, percent: number): number {
  return amount * (1 - percent / 100);
}

Invalid rate check

The discount rate must be between 0 and 100. Otherwise it is safer to return the amount unchanged. This prevents accidentally applying negative or very large discounts.

function applyDiscount(amount: number, percent: number): number {
  if (percent < 0 || percent > 100) {
    return amount;
  }
  return amount * (1 - percent / 100);
}

Practice Write the applyDiscount function

Write a function applyDiscount(amount: number, percent: number): number. If percent is not between 0 and 100, return amount unchanged. Otherwise return amount * (1 - percent / 100). Print three example calls: (100, 20), (50, 10), (200, 150).

Starter code

index.ts
// applyDiscount(amount: number, percent: number): number yaz
// percent 0 ile 100 arasında değilse amount'u değiştirmeden döndür
// geçerliyse indirimli tutarı hesapla
// üç örneği yazdır: (100, 20), (50, 10), (200, 150)

Sample solution

index.ts
function applyDiscount(amount: number, percent: number): number {
  if (percent < 0 || percent > 100) {
    return amount;
  }
  return amount * (1 - percent / 100);
}

console.log(applyDiscount(100, 20));
console.log(applyDiscount(50, 10));
console.log(applyDiscount(200, 150));

Expected output

80
45
200

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the price of 100 units after a 20% discount?

  • 100
  • 20
  • 80 Correct answer
  • 120

Explanation: Percentage discount: amount * (1 - percent / 100). 100 * (1 - 20/100) = 100 * 0.8 = 80.

2 Complete the discount formula

Question
return amount * (1 - ____ / 100);
Answer
return amount * (1 - percent / 100);

Explanation: The discount percentage is the percent variable. amount is the wrong variable; total and discount are not defined in this function.

3 Discount parts

Term Meaning
percent / 100 Convert rate to decimal
1 - percent / 100 Remaining rate
amount * (1 - percent / 100) Discounted price
percent < 0 || percent > 100 Invalid rate check

All lessons in Beginner