javaeclipse

Finding net salary from the gross salary and tax


The method should take the gross salary, calculate the tax amount, subtract it and return the net salary.

The tax rate will be applied by the following rules:

salary >= 45,000 pays a 50% tax rate, 
       >= 30,000 pays a 30% and 
          everyone else pays 15%.

Here is my code:

public double salaryTax(double salary) {
    
    double taxRate=0;
    
    if (salary >= 45.000) {
         taxRate = .5;
        
    }
    else if (salary >= 30.000) {
        taxRate = .3;
    }
    else
    {
        taxRate = .15;
    }
    double tax = salary * taxRate;
    double totalTax = tax + taxRate;
    double netSalary = salary - totalTax;
    return  netSalary;
}

However, whenever I test it, it is 0.5 away from the actual amount I am supposed to have.


Solution

  • Try this. Hope it will help

    public double salaryTax(double salary) {
    
        double taxRate = 0.15;
    
        if (salary >= 45000) {
             taxRate = 0.5;
    
        }
        else if (salary >= 30000) {
            taxRate = 0.3;
        }
    
        return  salary*(1.0- taxRate);
    }