Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java formula to compute discount dynamically

I need to implement an operation in my java program.

So I have the item, the price of it is 6,00€, but if the user get three of these items I can get a discount of 3,00€. So

int quantity = 3;
double discount = 3.0;
int quantityItem = 3;
double priceItem = 6.0;

double totalPrice = priceItem * quantityItem;
if(quantityItem == quantity){
   totalePrice = totalePrice - discount;
}

The previous code is ok. But if I get 5 items the correct totalePrice should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

priceItem (6€) * quantity (5) = 30€ – 3.0€ (discount) = 27€.

If I get 6 items the correct totalPrice should be:

priceItem (6€) * quantity (6) = 36€ – 6.0€ (discount) = 30€.

How can I write the code to make this dynamically ?

>Solution :

To identify the number of "groups of 3" of something bought, you need to divide the number bought by 3. Specifically, you want to use integer division, which basically means "divide by 3, then ignore the decimal part". So

1 / 3 = 0
2 / 3 = 0
3 / 3 = 1
4 / 3 = 1
5 / 3 = 1
6 / 3 = 2
...

In Java, division between two integers performs integer division by default, so you can calculate the number of "groups of 3" like so.

int discountQuantity = quantity / quantityItem;

Then you apply the discount that many times.

double totalPrice = priceItem * quantityItem - discountQuantity * discount;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading