Search code examples
javamethodscalc

How to calculate sales commission in java


I would like to know how I perform this calculation of the sales commission, I need to do the method and I'm not getting it. There is the value sold in relation to the goal, at first it would be less than 50% the seller earns only 1% and has the value sold in relation to the goal of 50 to 70% and the seller earns 2.5%. Where is the blank space of the if, is where I don’t know what to put, because I don’t know how to put less than half a value or even one value until the other, which in this case is 50 to 70%, e and from 71 to 100% you get 3.5%. I believe that the Sales Goal attribute needs to be in the method, because the program has to understand that the value sold was less than half of the goal.

public class Salesman {
    //defining attributes
    private String name;
    private double salesGoal;
    private double totalSold;

    public double calculateCommission() {
        double soldValue;
        if (totalSold <  ) {
            soldValue =(totalSold * 1.01);
        }else if(totalSold >= ){
            soldValue =(totalSold * 1.025);
        }else if(totalSold >= ){
            soldValue =(totalSold * 1.035);
        }else{
            soldValue = 0;
        }

        return soldValue;
    }

}

Solution

  • It helps to make some diagrams What goes in what goes out

    What goes in, and what goes out determines your method signature.

    public double calculateCommission(double soldValue, double goal) { 
      return 0d;
    }
    

    And then create some kind of flow diagram

    Flow diagram

    public double calculateCommissionRate(double soldValue, double goal) { 
      double ratio = soldValue / goal;
    
      if (ratio < 0.5) return 0.01;
      if (ratio < 0.7) return 0.025;
      return 0.035;
    }
    

    Try to think of your goal or sales target as a cake. What you need to know, is how much of the cake has been sold (ratio = sold/cake). That's the first thing to calculate.

    And a percentage is actually a ratio as well. "pro-cent" means x/100. so 50% is actually 50/100 , which is actually 0.5.

    So, we can just compare those 2 ratios directly with each other.


    I just realized that you may want to apply your commission-rate as well. In that case, you have to multiply it with the soldValue.

    public double calculateCommission(double soldValue, double goal) { 
      double commissionRate = calculateCommissionRate(soldValue, goal);
      return soldValue * commissionRate;
    }
    

    Final remark (out of scope): double is fine to store a ratio, but aren't that good for monetary values (i.e. the inputs of your method), due to all kind of rounding errors. You may want to use BigDecimal or alternatively, perhaps Integer and multiply your numbers by 100 to also store the decimals. Showing your values to the end user is then just a matter of using a decent formatter.