-1

I understand double as a variable type but in line 4 it might be used as datatype conversion. I just don't get the double used in line 6, am I completely missing the point here?

public static void main(String args[]) {
    int discountPercentage = 10;
    double totalPrice = 800;
    double priceAfterDiscount = totalPrice * (1 - ((double) discountPercentage / 100));
    if (totalPrice > 500) {
        priceAfterDiscount = priceAfterDiscount * (1 - ((double) 5 / 100));
    }
    System.out.println("Customer has paid a bill of amount: "+ priceAfterDiscount);
}
azro
  • 53,056
  • 7
  • 34
  • 70

1 Answers1

1

Writing 5 / 100 is an int division as both operand are ints, and in Java that will result in 0.

See Int division: Why is the result of 1/3 == 0?


To get 0.05, you need to make a division with double

  • define an operand as double explicitly

    5.0 / 100
    5 / 100.0
    
  • cast an operand

    (double) 5 / 100
    5 / (double) 100
    
azro
  • 53,056
  • 7
  • 34
  • 70