Mack
Mack

Reputation: 23

Calculate percentage using switch case

I am trying to create a prompt that asks for an amount of euro's, after that, depending on the input it will calculate the dicount, this is what I tried but it always shows the default value, how can I fix that?

var vraag = prompt("Omzet:");
var cijfer = parseInt(vraag);

switch(cijfer) {
    case cijfer >= 100:
    document.write(cijfer + "Kortingsbedrag = " + cijfer/100*10 + " euro" + "(Kortingspercentage is 10%)");
    break;
    case cijfer >= 500:
    document.write(cijfer + "Kortingsbedrag = " + cijfer/100*15 + " euro" + "(Kortingspercentage is 15%)");
    break;
    case cijfer >= 1000:
   document.write(cijfer + "Kortingsbedrag = " + cijfer/100*20 + " euro" + "(Kortingspercentage is 20%)");
    break;
    case  cijfer >= 2500:
    document.write(cijfer + "Kortingsbedrag = " + cijfer/100*25 + " euro" + "(Kortingspercentage is 25%)");
    break;    
    case cijfer >= 10000:
    document.write(cijfer + "Kortingsbedrag = " + cijfer/100*30 + " euro" + "(Kortingspercentage is 30%)");
    break;             
    default:
    document.write(cijfer + "Kortingsbedrag = " + cijfer/100*0 + " euro" + "(Kortingspercentage is 0%)");
}

Upvotes: 2

Views: 3058

Answers (2)

Gui Herzog
Gui Herzog

Reputation: 5615

Nina Scholz answer is absolutely right.

However, as it seems you do not have a lot of experience in programming (pardon me if I am wrong). I would like to add a few general suggestions:

  1. Avoid repetitions in your code by using document.write only once at the end of your switch.
  2. Use template literals in Javascript instead of string concat for putting variables inside strings.
  3. Take care of Division by Zero as your default case is exactly doing this.
  4. Use let/const instead of var because var is too generic.
  5. Use Number.parseInt() because it's more reliable;

Your code would look like this:

let vraag = prompt("Omzet:");
let cijfer = Number.parseInt(vraag);
let discount = 0;

switch (true) {
  case cijfer >= 100:
    discount = 0.1; //10%
    break;
  case cijfer >= 500:
    discount = 0.15; //15%
    break;
  case cijfer >= 1000:
    discount = 0.2; //20%
    break;
  case cijfer >= 2500:
    discount = 0.25; //25%
    break;
  case cijfer >= 10000:
    discount = 0.30; //30%
    break;
}

document.write(`${cijfer} Kortingsbedrag = ${cijfer*discount} euro (Kortingspercentage is ${discount*100}%)`);

I hope it helps! Good luck on your journey!

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386736

Your switchstatement need a value of the cases, because of the strict comparion of switch and case values.

You have a comparison in the cases parts and you need to test against true.

switch (true) {

Upvotes: 1

Related Questions